装饰模式可以将职责和使用相分离.
对于人穿衣服而言,其实人是不应该继承Finery的,但是装饰模式需要这样的封装和继承.书中的例子就违背了”细节依赖于抽象”,这里明显的是抽象依赖了细节,把两个完全独立的对象弄成了继承的关系.气人不.
装饰模式其实是抽象出了一系列同类对象,然后让这些对象互相之间都能装饰.主要是体现在两个方法上: decorate() 和 show() , 又把shou()提高为最高接口,让两种不同的类(Person 和 服饰)进行关联,(Person类是没有decorate方法的).
1 2 3 4 5 6 7 8 9
| package decorator;
public abstract class Finery { public abstract void show(); }
|
1 2 3 4 5 6 7 8 9 10 11 12
| package decorator;
public class Tshirt extends Decorator { public void show() { super.show(); System.out.println("wear T shirt"); } }
|
1 2 3 4 5 6 7 8 9 10 11 12
| package decorator;
public class Pans extends Decorator { public void show() { super.show(); System.out.println("wear pans"); } }
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| package decorator;
public class Person extends Finery { private String name;
public Person(String name){ this.name = name; }
public void show() { System.out.println(name + " dress:"); } }
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| package decorator;
public class Decorator extends Finery { private Finery component;
public void decorate(Finery component) { this.component = component; }
public void show() { if (component != null) { component.show(); } } }
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| package decorator;
public class Main { public static void main(String[] args) { Person person = new Person("小明"); Decorator d1 = new Pans(); Decorator d2 = new Tshirt(); d1.decorate(person); d2.decorate(d1); d2.show(); } }
|