题目:给一个人“小王”搭配衣服和裤子
public abstract class Component { public abstract void operation(); }
public class ConcreteComponent extends Component { @Override public void operation() { System.out.println("具体对象的操作"); } }
public abstract class Decorator extends Component { protected Component component; public void setComponent(Component component) { this.component = component; } @Override public void operation() { if (component != null) { component.operation(); } } }
public class ConcreteDecoratorA extends Decorator { private String addedState; @Override public void operation() { super.operation(); addedState = "New State"; System.out.println("具体装饰对象A的操作"); } }
public class ConcreteDecoratorB extends Decorator { @Override public void operation() { super.operation(); addBehavior(); System.out.println("具体装饰对象B的操作"); } private void addBehavior() { } }
public class Wear { public static void main(String args[]){ ConcreteComponent c = new ConcreteComponent(); ConcreteDecoratorA d1 = new ConcreteDecoratorA(); ConcreteDecoratorB d2 = new ConcreteDecoratorB(); d1.setComponent(c); d2.setComponent(d1); d2.operation(); } }
特别注意这段
d1.setComponent(c); d2.setComponent(d1); d2.operation();
一层套一层,代表功能的拓展
装饰者模式是利用setComponent进行包装的
另外,如果只有一个ConcreteComponent类而没有抽象的Component类,那Decorator类可以是ConcreteComponent的一个子类。
如果只有一个ConcreteDecorator类,那么就没有必要建立一个单独的Decorator类,而可以把Decorator和ConcreteDecorator的责任合并成一个类。
public class Person { private String name; public Person() { } public Person(String name) { this.name = name; } public void show() { System.out.println("装扮的" + name); } }
public class Decorator extends Person { protected Person component; public void Decorator(Person component) { this.component = component; } @Override public void show() { if (component != null) { component.show(); } } }
public class TShirt extends Decorator { @Override public void show() { System.out.println("大T恤"); super.show(); } }
public class BigTrouser extends Decorator { @Override public void show() { System.out.println("垮裤"); super.show(); } }
public class Wear { public static void main(String args[]) { Person person = new Person("小王"); TShirt tShirt = new TShirt(); BigTrouser bigTrouser = new BigTrouser(); tShirt.Decorator(person); bigTrouser.Decorator(tShirt); bigTrouser.show(); } }
tShirt.Decorator(person);
bigTrouser.Decorator(tShirt);
bigTrouser.show();
就是装饰过程
时间: 2024-10-12 19:40:38