设计模式之装饰模式
1. 作用
动态地给对象添加一些额外的功能,并且将所需的功能按照一定的顺序串联起来。
2. 例子
以奶茶加料计算价格为例,现在点一杯奶茶,茶底(2元),可以加的小料有珍珠(2元)、椰果(1元)、奶冻(3元)…
由此,我们可以写出的类结构如下
(个人觉得,在本例中,~milkyTea 那条线可以是组合也可以是关联)
代码如下
package Decorator;
/**
* 奶茶类
*/
public abstract class MilkyTea {
double price;
public MilkyTea(double price) {
this.price = price;
}
public double cost(){
return 0;
}
}
package Decorator;
package Decorator;
/**
* 茶底类 继承奶茶类
*/
public class Tea extends MilkyTea{
public Tea(){
super(2);
}
@Override
public double cost() {
return this.price;
}
}
package Decorator;
/**
* 小料类
* 每个小料都加入
*/
public abstract class SmallMaterial extends MilkyTea{
MilkyTea milkyTea;
public SmallMaterial(MilkyTea milkyTea) {
super(milkyTea.price);
this.milkyTea=milkyTea;
}
}
package Decorator;
/**
* 珍珠类,继承小料
*/
class Pearl extends SmallMaterial{
public Pearl(MilkyTea milkyTea){
super(milkyTea);
this.price=2;
}
@Override
public double cost() {
return milkyTea.cost()+this.price;
}
}
/**
* 椰果;类,继承小料
*/
class NataDeCoco extends SmallMaterial{
public NataDeCoco(MilkyTea milkyTea){
super(milkyTea);
this.price=1;
}
@Override
public double cost() {
return milkyTea.cost()+this.price;
}
}
/**
* 奶冻类继承小料
*/
class Custard extends SmallMaterial{
public Custard(MilkyTea milkyTea){
super(milkyTea);
this.price=3;
}
@Override
public double cost() {
return milkyTea.cost()+this.price;
}
}
package Decorator;
public class Test {
public static void main(String[] args) {
MilkyTea milkyTea=new Tea(); //创建茶底对象
MilkyTea pearl=new Pearl(milkyTea); //珍珠(2元)+奶茶(2元)
System.out.println(pearl.cost()); //4.0
MilkyTea natadecoco=new NataDeCoco(pearl); //珍珠(2元)+奶茶(2元)+椰果(1元)
System.out.println(natadecoco.cost()); //5.0
MilkyTea natadecoco2=new NataDeCoco(milkyTea); //奶茶(2元)+椰果(1元)
System.out.println(natadecoco2.cost()); //3.0
MilkyTea custard = new Custard(natadecoco); //珍珠(2元)+奶茶(2元)+椰果(1元)+奶冻(3元)
System.out.println(custard.cost()); //8.0
}
}
3. 装饰模式结构图
4. java中的装饰模式
public abstract class InputStream implements Closeable {}
public class FilterInputStream extends InputStream {
/**
* The input stream to be filtered.
*/
protected volatile InputStream in;
}
public class BufferedInputStream extends FilterInputStream {}
package Decorator;
import java.io.BufferedInputStream;
import java.io.FileInputStream;
public class Test {
public static void main(String[] args) {
try {
FileInputStream fis = new FileInputStream("src/Decorator/a.txt");
BufferedInputStream bif = new BufferedInputStream(fis);
System.out.println(bif.read());
} catch (Exception e) {
e.printStackTrace();
}
}
}
如果觉得这篇博客写的还不错的,那就点个赞鼓励一下吧!欢迎大家在评论区一起讨论。