一. 概念Decorator(装饰模式):动态地给一个对象添加一些额外的职责。就扩展功能而言, 它比生成子类方式更为灵活。
二. 角色抽象构件(Component)角色:给出一个抽象接口,以规范准备接收附加责任的对象。 具体构件(ConcreteComponent)角色:定义一个将要接收附加责任的类。 装饰(Decorator)角色:持有一个构件(Component)角色对象的实例,并定义一个与抽象构件接口一致的接口。 具体装饰(ConcreteDecorator)角色:负责给构件对象贴上附加的责任。
三. 实现一个人往往有许多身份,比如一个男人,他是一个人,同时也可能是父亲,丈夫,也可能是程序员,这是父亲、丈夫和程序员就是具体装饰角色,人则是抽象构件角色,男人则为具体构件角色。
Test.java public class Test { public static void main(String[] args) { Decorator fatherDecorator = new FatherDecorator(); Decorator husbandDecorator = new HusbandDecorator(); Decorator programmerDecorator = new Programmer(); Human like = new Male(); fatherDecorator.setHuman(like); husbandDecorator.setHuman(fatherDecorator); programmerDecorator.setHuman(husbandDecorator); programmerDecorator.work(); } } 测试类,定义一个Human,分别给他装饰丈夫,父亲和程序员。
Human.java public interface Human { public void work(); } 人类,为抽象构件角色。
Male.java public class Male implements Human {
@Override public void work() { System.out.println("好好活着"); } } 男人类,继承与人类,是具体构件角色。
Decorator.java public class Decorator implements Human { private Human human;
public Human getHuman() { return human; }
public Decorator setHuman(Human human) { this.human = human; return this; } public Decorator(){ }
public Decorator(Human human) { super(); this.human = human; }
@Override public void work() { this.human.work(); } } 装饰角色。其中有一个抽象构件的对象。
FatherDecorator.java public class FatherDecorator extends Decorator { @Override public void work(){ System.out.println("保护孩子"); super.getHuman().work(); } } 父亲装饰类,具体装饰类。
HusbandDecorator.java public class HusbandDecorator extends Decorator { @Override public void work(){ System.out.println("保护妻子"); super.getHuman().work(); } } 丈夫装饰类,具体装饰类。
Programmer.java public class Programmer extends Decorator { @Override public void work(){ System.out.println("写好程序"); super.getHuman().work(); } } 程序员类,具体装饰类。
|