站长工具亚洲中文精品,设计网站公司都选亿企邦,免费素材视频软件app,长沙抖音代运营一、介绍#xff1a;
1、应用场景#xff1a;把所需的功能按正确的顺序串联起来进行控制。动态地给一个对象添加一些额外的职责#xff0c;就增加功能来说#xff0c;装饰模式比生成子类更加灵活。
当需要给一个现有类添加附加职责#xff0c;而又不能采用生成子类的方法…一、介绍
1、应用场景把所需的功能按正确的顺序串联起来进行控制。动态地给一个对象添加一些额外的职责就增加功能来说装饰模式比生成子类更加灵活。
当需要给一个现有类添加附加职责而又不能采用生成子类的方法进行扩充时。例如该类被隐藏或者该类是终极类或者采用继承方式会产生大量的子类。当需要通过对现有的一组基本功能进行排列组合而产生非常多的功能时采用继承关系很难实现而采用装饰模式却很好实现。当对象的功能要求可以动态地添加也可以再动态地撤销时。
2、类图 package decorator;
public class DecoratorPattern
{public static void main(String[] args){Component pnew ConcreteComponent();p.operation();System.out.println(---------------------------------);Component dnew ConcreteDecorator(p);d.operation();}
}//1、
//抽象构件角色
interface Component
{public void operation();
}//2、
//具体构件角色
class ConcreteComponent implements Component
{public ConcreteComponent(){System.out.println(创建具体构件角色); } public void operation(){System.out.println(调用具体构件角色的方法operation()); }
}//3、
//抽象装饰角色
class Decorator implements Component
{private Component component; public Decorator(Component component){this.componentcomponent;} public void operation(){component.operation();}
}//4、
//具体装饰角色
class ConcreteDecorator extends Decorator
{public ConcreteDecorator(Component component){super(component);} public void operation(){super.operation();addedFunction();}public void addedFunction(){System.out.println(为具体构件角色增加额外的功能addedFunction()); }
}
3、装饰模式简化 装饰模式所包含的 4 个角色不是任何时候都要存在的在有些应用环境下模式是可以简化的如以下两种情况。
1如果只有一个具体构件而没有抽象构件时可以让抽象装饰继承具体构件。如人穿衣服没必要写Component类可以让服饰类Decorator继承人类ConcreteComponent即可。 2 如果只有一个具体装饰时可以将抽象装饰和具体装饰合并 二、实例
1、装饰模式在 Java 语言中的最著名的应用莫过于 Java I/O 标准库的设计了。例如InputStream 的子类 FilterInputStreamOutputStream 的子类 FilterOutputStreamReader 的子类 BufferedReader 以及 FilterReader还有 Writer 的子类 BufferedWriter、FilterWriter 以及 PrintWriter 等它们都是抽象装饰类。
BufferedReader innew BufferedReader(new FileReader(filename.txtn));
String sin.readLine();
2、游戏中的变身组合服装
3、房子装修