标签:
package itcast.test.decorator; /** * 装饰器的接口,需要和被装饰的对象实现同样的接口*/ public abstract class Dercorator implements GoodsSaleEbi { /** * 持有被装饰的组件对象*/ protected GoodsSaleEbi ebi; /** * 通过构造方法传入被装饰对象 * @prara, ebi被装饰的对象*/ public Dercorator(GoodsSaleEbi ebi){ this.ebi=ebi; } } package itcast.test.decorator; public class CheckDecorator extends Dercorator{ /** * 实现权限控制*/ public CheckDecorator(GoodsSaleEbi ebi){ super(ebi); } public boolean sale(String user,String customer,SaleModel saleModel){ //简单点儿,只让张三执行这个功能 if(!"张三".equals(user)){ System.out.println("对不起"+user+",你没有保存销售单的权限"); //就不用再调用被装饰的对象的功能了 return false; }else{ return this.ebi.sale(user,customer,saleModel); } } } package itcast.test.decorator; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; public class LogDercorator extends Dercorator{ public LogDercorator(GoodsSaleEbi ebi){ super(ebi); } public boolean sale(String user,String customer,SaleModel saleModel){ //执行业务功能 boolean f= this.ebi.sale(user, customer, saleModel); //执行业务功能后记录日志 DateFormat df= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss SSS"); System.out.println("日志记录:"+user+"于"+df.format(new Date())+"时保存了一条销售记录,客户是"+customer+",购买记录是"+saleModel); return f; } } package itcast.test.decorator; //商品销售管理的业务接口 public interface GoodsSaleEbi { /* * 保存销售信息 * @param customer 客户 * @param saleModel 销售数据 * @return 是否保存成功*/ public boolean sale(String user,String customer,SaleModel saleModel); } package itcast.test.decorator; public class GoodsSaleEbo implements GoodsSaleEbi { @Override public boolean sale(String user, String customer, SaleModel saleModel) { System.out.println(user+"保存了"+customer+"购买"+saleModel+"的销售数据"); return true; } } package itcast.test.decorator; /** * 封装好的销售单数据对象*/ public class SaleModel { private String goods; private int saleNum; public String getGoods() { return goods; } public void setGoods(String goods) { this.goods = goods; } public int getSaleNum() { return saleNum; } public void setSaleNum(int saleNum) { this.saleNum = saleNum; } public String toString(){ return "商品名称="+goods+",购买数量="+saleNum; } } package itcast.test.decorator; public class Client { public static void main(String[] args){ //得到业务接口,组合装饰器 GoodsSaleEbi ebi = new CheckDecorator(new LogDercorator(new GoodsSaleEbo())); /*准备测试数据*/ SaleModel saleModel= new SaleModel(); saleModel.setGoods("MoTo 手机"); saleModel.setSaleNum(2); //调用和业务功能 ebi.sale("张三", "张三丰", saleModel); ebi.sale("李四", "张三丰", saleModel); } }运行结果:
标签:
原文地址:http://blog.csdn.net/wangdan1030/article/details/51502757