首页 > 学院 > 开发设计 > 正文

Java-马士兵设计模式学习笔记-装饰者模式

2019-11-15 00:34:47
字体:
来源:转载
供稿:网友
java-马士兵设计模式学习笔记-装饰者模式

Java装饰者模式简介

一、假设有一个Worker接口,它有一个doSomething方法,Plumber和Carpenter都实现了Worker接口,代码及关系如下:

1.Worker.javapackage decorator;public interface Worker {    public void doSomething();}

2.Plumber.javapublic class Plumber implements Worker {    @Override    public void doSomething() {        System.out.PRintln("修理水管");    }}

3.Carpenterpublic class Carpenter implements Worker{    public void doSomething(){        System.out.println("修门窗");    }}
4.测试代码 Test.javapublic class Test {    public static void main(String[] args) {        Worker worker = null;        Carpenter carpenter = new Carpenter();        Plumber plumber = new Plumber();        worker = carpenter;        worker.doSomething();        worker = plumber;        worker.doSomething();    }}

测试结果如下:

二、现有A、B两家公司,都有木工(Carpenter)和水管工(Plumber),但两公司的对两个工种的要求都不同,A公司要求员工在doSomething前自己介绍“我是A公司的”;B公司要求员工在doSomething前自己介绍“我是B公司的”;一个直接但不科学的设计方法是为每个公司都设计各自的木工(Carpenter)和水管工(Plumber),若公司增加到100个,则类要增加到200个,若再增加其他工种,则类会更多,关系如下:

三、此情况适合采用装饰者模式,为每个公司设计一个装饰类xWorker,xWorker也实现Worker接口,且有一个参数类型为Worker的构造函数和一个类型为Worker的成员变量,这样xWorker就可以取得相应类型worker的引用,在xWorker的doSomething()方法里处理各自公司的特殊要求:

 1 增加类 AWorker.java 2  3 public class AWorker implements Worker { 4  5     private Worker worker; 6      7     //通过些构造函数,AWorker就可以得到具体工种的引用, 8     //为下面的doSomething()方法中加入A公司的特殊要求做准备 9     public AWorker(Worker worker){10         this.worker = worker;11     }12     13     @Override14     public void doSomething() {15         System.out.println("您好!我是A公司的员工");16         worker.doSomething();17     }18 19 }

 1 //增加类 BWorker.java 2  3 public class BWorker implements Worker { 4  5     private Worker worker; 6      7     public BWorker(Worker worker){ 8         this.worker = worker; 9     }10     11     @Override12     public void doSomething() {13         System.out.println("您好!我是B公司的员工。");14         worker.doSomething();15     }16 17 }

 1 //测试代码 2      3 public static void main(String[] args) { 4          5         //A公司 6         Carpenter carpenterA = new Carpenter(); 7         Plumber plumberA = new Plumber(); 8         AWorker aWorker1 = new AWorker(carpenterA); 9         AWorker aWorker2 = new AWorker(plumberA);10         11         aWorker1.doSomething();12         aWorker2.doSomething();13     14         System.out.println("==================================");15         16         //B公司17         Carpenter carpenterB = new Carpenter();18         Plumber plumberB = new Plumber();19         BWorker bWorker1 = new BWorker(carpenterB);20         BWorker bWorker2 = new BWorker(plumberB);21         22         bWorker1.doSomething();23         bWorker2.doSomething();24     }25 }

测试结果:


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表