您的位置:首页 > 编程语言 > Java开发

设计模式--装饰模式

2016-04-08 00:00 239 查看
摘要: 简单记录装饰模式的使用。

装饰模式(decorator,别名Wrapper):

给一个对象增加一些新的功能,而且是动态的,要求装饰对象和被装饰对象实现同一个接口,装饰对象持有被装饰对象的实例。

装饰器模式的应用场景:

1.需要扩展一个类的功能。
2.动态的为一个对象增加功能,而且还能动态撤销。

装饰器模式的缺点:

1.产生过多相似的对象,不易排错

示例:

装饰者模式测试类GirlDecoratorTest.java

/**
* 装饰者模式测试类
*
* @author Kevin
* @date 2016-3-15
*/
public class GirlDecoratorTest {

public static void main(String[] args) {
ChineseGirlImpl girl = new ChineseGirlImpl();
GirlDecoratorImpl decorator = new GirlDecoratorImpl(girl);
decorator.description();
}
}

描述接口类Description.java

/**
* 描述接口
*
* @author Kevin
* @date 2016-3-15
*/
public interface Description {

/**
* 描述
*
* @author Kevin
*/
void description();
}

中国女孩类(被装饰类)ChineseGirlImpl.java

/**
* 中国女孩类(被装饰类)
*
* @author Kevin
* @date 2016-3-15
*/
public class ChineseGirlImpl implements Description {

@Override
public void description() {
System.out.println("ChineseGirl goodness");
}
}

女孩装饰类(装饰类,可以为被装饰类添加功能)GirlDecoratorImpl.java

/**
* 女孩装饰类(装饰类,可以为被装饰类添加功能)
*
* @author Kevin
* @date 2016-3-15
*/
public class GirlDecoratorImpl implements Description {

/* 中国女孩类(被装饰类) */
private ChineseGirlImpl chineseGirl;

public GirlDecoratorImpl() {

}

public GirlDecoratorImpl(ChineseGirlImpl chineseGirl) {
this.chineseGirl = chineseGirl;
}

@Override
public void description() {
System.out.println("before decorator");
chineseGirl.description();
System.out.println("after decorator");
System.out.println("chineseGirl goodness and beautiful");
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息