您的位置:首页 > 其它

设计模式之装饰者模式

2016-07-07 18:50 323 查看
一、什么事装饰者模式

定义:在不必改变原类文件和使用继承的情况下,动态地扩展一个对象的功能。它是通过创建一个包装对象,也就是装饰来包裹真实的对象。

二、装饰者模式适合什么场景

适用场景:

1.需要动态的给一个对象添加功能,这些功能可以再动态的撤销

2.需要增加由一些基本功能的排列组合而产生的非常大量的功能,从而使继承关系变的不现实

3当不能采用生成子类的方法进行扩充时

三、装饰者模式类图

四、装饰者模式应用

IO流

五、实例浅析装饰者模式

1、创建一个公共接口,在接口里声明需要的属性和方法

2、创建要被装饰的具体类,实现公共接口

3,创建装饰者类,实现公共接口

4、测试

(注释:装饰者类和被装饰者具体类同是实现公共接口,因此他们实际上是同属于一类的)

公共接口的创建:

package DecoratorModel;
/*
* 公共接口
*/
public interface Fruit {
//得到价格
public float getPrice();
//描述的方法
public String descirbe();
}
被装饰者的具体类创建

package DecoratorModel;
/*
* 创建一个被装饰的具体类,实现接口
*/
public class Apple implements Fruit{
//得到价格
public float getPrice() {
return 8.0f;
}
//描述的方法
public String descirbe() {
return "这是苹果";
}

}


装饰者具体类创建

0号装饰者

package DecoratorModel;
/*
* 装饰类0
*/
public class Decorator implements Fruit {
private Fruit fruit;
//装饰方法
public Decorator(Fruit fruit) {
this.fruit = fruit;
}
//得到价格
public float getPrice() {
return 0;
}
//描述的方法
public String descirbe() {
return null;
}

}
1号装饰者

package DecoratorModel;
/*
* 装饰类1
*/
public class RedDecorator extends Decorator {
private Fruit fruit;
//装饰方法
public RedDecorator(Fruit fruit) {
super(fruit);
this.fruit = fruit;
}
//得到价格
public float getPrice() {
return fruit.getPrice() + 4;
}
//描述的方法
public String descirbe(){
return  fruit.descirbe()+"而且很红";
}
}
2号装饰者

package DecoratorModel;
/*
* 装饰类2
*/
public class BigDecorator extends Decorator {
private Fruit fruit;
//装饰方法1
public BigDecorator(Fruit fruit) {
super(fruit);
this.fruit = fruit;
}
//得到价格
public float getPrice() {
return fruit.getPrice() + 2;
}
//描述的方法
public String describe() {
return fruit.descirbe()+"也很大";
}
}


测试类

package DecoratorModel;

public class Test {
public static void main(String[] args){
Apple apple = new Apple();
//输出apple的价格和描述
System.out.println(apple.getPrice());
System.out.println(apple.descirbe());
//对apple进行一层装饰
RedDecorator redApple = new RedDecorator(apple);
System.out.println(redApple.getPrice());
System.out.println(redApple.descirbe());
//对apple进行二层装饰,即对redApple进行一层装饰
BigDecorator bigApple = new BigDecorator(redApple);
System.out.println(bigApple.getPrice());
System.out.println(bigApple.describe());
}
}
不想那么官方地描述思想,简单点就是通过同类的类的方法进行在原来的基础上添加修饰。好吧,就这样,哈哈。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: