使用Decorator模式相比用生成子类方式达到功能的扩充显得更为灵活。
继承:对于所有可能的联合,客户期望很容易增加任何的 困难
下面通过一个实例来对比装饰模式和继承的区别。
class Person{ void eat(){ System.out.println("吃饭"); } }
//NewPerson,Man,Woman同属于Person体系中,要拓展Man或者Woman的eat功能
//不需要通过Man或者Woman的子类来实现,可以把拓展功能统一定义在NewPerson(装饰类)中。
//进而在Man或者Woman拓展功能时直接被NewPerson装饰就可以实现功能拓展。
class NewPerson extends Person{ private Person p; NewPerson(Person p){ this.p=p; } void eat(){ System.out.println("开胃酒"); p.eat(); System.out.println("吃点水果"); } } class Woman extends Person{ void eat(){ System.out.println("女人吃饭"); } } class Man extends Person{ void eat(){ System.out.println("男人吃饭"); } }
如通过子类继承来拓展Man类的eat功能
//如果想增强男人的eat功能,就要继承Man,这样通过子类SubMan来增强。 class SubMan extends Man{ void eat(){ System.out.println("开胃酒"); super.eat(); System.out.println("吃点水果"); System.out.println("饭后来根烟"); } }
通过继承来拓展Woman类的eat功能还需要像Man一样,这样最好导致代码比较臃肿,为了避免这种臃肿,同时为了提高效率,就用到了装饰模式。
class Man extends Person{ void eat(){ System.out.println("男人吃饭"); } } //如果想增强男人的eat功能,就要继承Man,这样通过子类SubMan来增强。 class SubMan extends Man{ void eat(){ System.out.println("开胃酒"); super.eat(); System.out.println("吃点水果"); System.out.println("饭后来根烟"); } } class SubWoman extends Woman{ void eat(){ System.out.println("开胃酒"); super.eat(); System.out.println("吃点水果"); System.out.println("饭后来根烟"); } }
二:装饰模式
通过装饰模式来要拓展Man或者Woman的eat功能,就没必要再生成子类了
NewPerson,Man,Woman同属于Person体系中,要拓展Man或者Woman的eat功能
不需要通过Man或者Woman的子类来实现,可以把拓展功能统一定义在NewPerson(装饰类)中。
进而在Man或者Woman拓展功能时直接被NewPerson装饰就可以实现功能拓展。
写完后调用一下试试。
public static void main(String[]args){ <span style="white-space:pre"> </span> <span style="white-space:pre"> </span> <span style="white-space:pre"> </span>Man m=new Man(); <span style="white-space:pre"> </span>NewPerson newm=new NewPerson(m); <span style="white-space:pre"> </span>newm.eat(); <span style="white-space:pre"> </span> <span style="white-space:pre"> </span>Woman w=new Woman(); <span style="white-space:pre"> </span>NewPerson ww=new NewPerson(w); <span style="white-space:pre"> </span>ww.eat(); <span style="white-space:pre"> </span> <span style="white-space:pre"> </span>}
开胃酒
男人吃饭
吃点水果
饭后来根烟
开胃酒
女人吃饭
吃点水果
饭后来根烟
后面我会陆续为大家介绍剩下的22中设计模式。。。。。。。。。。。。。