设计模式之装饰器模式
如果现在有个需求,让你定义一个男人戴帽子。你会先定义一个人的接口,然后男人实现接口,并加入戴帽子的方法。但是如果再让你加上穿衣服的功能,在不改变原有代码的基础上,你会写一个继承类实现穿衣服的功能。但是需求又增多了呢,那么就造成继承类太多,这个时候就可以用装饰器模式。
先定义person接口
public interface Person {
void show();
}
在定义男人类实现接口
public class Man implements Person {
@Override
public void show() {
System.out.println("我是男人");
}
}
定义抽象装饰器类
public abstract class PersonDecorator implements Person {
protected Person DecoratorPerson;
public PersonDecorator(Person DecoratorPerson) {
this.DecoratorPerson = DecoratorPerson;
}
@Override
public void show() {
DecoratorPerson.show();
}
}
具体帽子装饰器类
public class CapPersonDecorator extends PersonDecorator {
public CapPersonDecorator(Person DecoratorPerson) {
super(DecoratorPerson);
}
@Override
public void show() {
super.show();
setTake(DecoratorPerson);
}
private void setTake(Person DecoratorPerson){
System.out.println("戴帽子");
}
}
具体衣服装饰器类
public class ClosePersonDecorator extends PersonDecorator {
public ClosePersonDecorator(Person DecoratorPerson) {
super(DecoratorPerson);
}
@Override
public void show() {
DecoratorPerson.show();
setTake(DecoratorPerson);
}
private void setTake(Person DecoratorPerson){
System.out.println("穿衣服");
}
}
客户端测试类
public class test {
public static void main(String[] args) {
// Person person1=new CapPersonDecorator(
new ClosePersonDecorator(new Man()));
//
// person1.show();
// System.out.println();
//也可以写成下面的写法
Person person=new Man();
Person person2=new ClosePersonDecorator(person);
Person person3=new CapPersonDecorator(person2);
person3.show();
}
}