java 装饰者模式
IPerson:
/* @author com.tiantian
@version 创建时间:2012-11-20 下午3:43:04
/
public interface IPerson {
public void canDo();
}
Person:
/* @author com.tiantian
@version 创建时间:2012-11-20 下午3:44:04
/
public class Person implements IPerson{
@Override
public void canDo() {
System.out.println(“I can code”);
}
}
Decorator(所有Person装饰者的父类):
/* @author com.tiantian
@version 创建时间:2012-11-20 下午3:44:55
/
public class Decorator implements IPerson{
private IPerson person;
public Decorator(IPerson person) {
this.person = person;
}
@Override
public void canDo() {
person.canDo();
}
}
DecoratorSwim(Swim装饰–为Peron添加“Swim”功能):
/* @author com.tiantian
@version 创建时间:2012-11-20 下午3:48:54
/
public class DecoratorSwim extends Decorator{
public DecoratorSwim(IPerson person) {
super(person);
}
@Override
public void canDo() {
super.canDo();
System.out.println(“I also can swim”);
}
}
DecoratorDraw(Draw装饰–为Peron添加“Draw”功能):
/* @author com.tiantian
@version 创建时间:2012-11-20 下午3:47:29
/
public class DecoratorDraw extends Decorator{
public DecoratorDraw(IPerson person) {
super(person);
}
@Override
public void canDo() {
super.canDo();
System.out.println(“I also can draw”);
}
}
Test:
/* @author com.tiantian
@version 创建时间:2012-11-20 下午3:49:35
/
public class Test {
public static void main(String[] args) {
Decorator decorator = new DecoratorDraw(new DecoratorSwim(new Person()));
decorator.canDo();
}
}
来源博客:Wang Jie's Blog's Blog
本文链接:https://blog.wangjiegulu.com/2012/11/20/java-装饰者模式/
版权声明:本博客所有文章除特别声明外,均采用 CC BY 4.0 CN协议 许可协议。转载请注明出处。
本文链接:https://blog.wangjiegulu.com/2012/11/20/java-装饰者模式/
版权声明:本博客所有文章除特别声明外,均采用 CC BY 4.0 CN协议 许可协议。转载请注明出处。