什么是装饰者模式?
装饰器模式是一种结构设计模式,它动态地将附加行为附加到对象上。装饰器通过组合而不是子类化(继承)提供灵活的扩展原因。
什么时候使用它?
当您想通过在运行时添加小行为来构造对象时,请使用装饰器模式。
UML图
装饰器类使用组合和继承,理解它们的意图至关重要。
在装饰器模式中,我们对组件和装饰器使用相同的类型。 Decorator 复合 Component 对象来获取行为,即获取 Component 对象中定义的字段或方法。而Decorator继承(扩展)了Component,使得Decorator对象可以声明为Component对象。
装饰器模式实现了开闭原则,即对扩展开放,对修改封闭。添加组件或装饰器很容易。例如,如果你想添加另一个具体的装饰器,你只需要创建一个代表它的类并扩展装饰器类。
例子
想象一下我们正在为一家冰淇淋店开发一个系统。店里有各种冰淇淋和配料。系统需要显示冰淇淋的描述(包括其配料)和成本。
- 组件(冰淇淋)和装饰器(配料)有公共接口 IceCream 类,它们都声明为 IceCream 对象。
- 每种具体冰淇淋都会覆盖成本法,因为每种冰淇淋的价格都不同。
- Topping 类提供具体浇头的接口并保存对 IceCream 的引用。
- 如果系统需要其他配料,比如焦糖源,您需要做的就是创建扩展 Topping 类的 CaramelSource 类。
Java 中的实现
冰淇淋课:
// Component class public abstract class IceCream { public String description = "Unknown ice cream"; public String getDescription() { return description; } public abstract double cost(); }
巧克力冰淇淋类:
// Concrete component class public class ChocolateIceCream extends IceCream { public ChocolateIceCream() { description = "ChocolateIceCream"; } @Override public double cost() { return 1.99; } }
顶级班:
// Base decorator class public abstract class Topping extends IceCream { public IceCream iceCream; // All subclasses (concrete decorator classes) need to implement getDescription method, // by declaring this method as abstract, we enforce all subclasses to implement this method public abstract String getDescription(); }
枫坚果类:
// Concrete decorator class public class MapleNuts extends Topping { public MapleNuts(IceCream iceCream) { this.iceCream = iceCream; } @Override public String getDescription() { return iceCream.getDescription() + ", MapleNuts"; } @Override public double cost() { return iceCream.cost() + .30; } }
PeanutButterShell 类:
// Concrete decorator class public class PeanutButterShell extends Topping { public PeanutButterShell(IceCream iceCream) { this.iceCream = iceCream; } @Override public String getDescription() { return iceCream.getDescription() + ", PeanutButterShell"; } @Override public double cost() { return iceCream.cost() + .30; } }
客户端类:
public class Client { public static void main(String[] args) { IceCream iceCream = new ChocolateIceCream(); System.out.println(iceCream.getDescription() + ", $" + iceCream.cost()); iceCream = new MapleNuts(iceCream); System.out.println(iceCream.getDescription() + ", $" + iceCream.cost()); iceCream = new PeanutButterShell(iceCream); System.out.println(iceCream.getDescription() + ", $" + iceCream.cost()); } }
输出:
ChocolateIceCream, .99 ChocolateIceCream, MapleNuts, .29 ChocolateIceCream, MapleNuts, PeanutButterShell, .59
您可以在这里查看所有设计模式的实现。
GitHub 存储库
附注
我是刚开始写科技博客,如果您对我的写作有什么建议,或者有任何困惑的地方,请留言!
感谢您的阅读:)
以上是装饰模式的详细内容。更多信息请关注PHP中文网其他相关文章!

JavaachievesPlatFormIndependencethroughTheJavavIrtualMachine(JVM),允许Codetorunondifferentoperatingsystemsswithoutmodification.thejvmcompilesjavacodeintoplatform-interploplatform-interpectentbybyteentbytybyteentbybytecode,whatittheninternterninterpretsandectectececutesoneonthepecificos,atrafficteyos,Afferctinginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginging

JavaispoperfulduetoitsplatFormitiondence,对象与偏见,RichstandardLibrary,PerformanceCapabilities和StrongsecurityFeatures.1)Platform-dimplighandependectionceallowsenceallowsenceallowsenceallowsencationSapplicationStornanyDevicesupportingJava.2)

Java的顶级功能包括:1)面向对象编程,支持多态性,提升代码的灵活性和可维护性;2)异常处理机制,通过try-catch-finally块提高代码的鲁棒性;3)垃圾回收,简化内存管理;4)泛型,增强类型安全性;5)ambda表达式和函数式编程,使代码更简洁和表达性强;6)丰富的标准库,提供优化过的数据结构和算法。

javaisnotirelyPlatemententduetojvmvariationsandnativecodinteintration,butitlargelyupholdsitsitsworapromise.1)javacompilestobytecoderunbythejvm

thejavavirtualmachine(JVM)IsanabtractComputingmachinecrucialforjavaexecutionasitrunsjavabytecode,使“ writeononce,runanywhere”能力

Javaremainsagoodlanguageduetoitscontinuousevolutionandrobustecosystem.1)Lambdaexpressionsenhancecodereadabilityandenablefunctionalprogramming.2)Streamsallowforefficientdataprocessing,particularlywithlargedatasets.3)ThemodularsystemintroducedinJava9im

Javaisgreatduetoitsplatformindependence,robustOOPsupport,extensivelibraries,andstrongcommunity.1)PlatformindependenceviaJVMallowscodetorunonvariousplatforms.2)OOPfeatureslikeencapsulation,inheritance,andpolymorphismenablemodularandscalablecode.3)Rich

Java的五大特色是多态性、Lambda表达式、StreamsAPI、泛型和异常处理。1.多态性让不同类的对象可以作为共同基类的对象使用。2.Lambda表达式使代码更简洁,特别适合处理集合和流。3.StreamsAPI高效处理大数据集,支持声明式操作。4.泛型提供类型安全和重用性,编译时捕获类型错误。5.异常处理帮助优雅处理错误,编写可靠软件。


热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

Video Face Swap
使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

Dreamweaver Mac版
视觉化网页开发工具

SublimeText3 Mac版
神级代码编辑软件(SublimeText3)

EditPlus 中文破解版
体积小,语法高亮,不支持代码提示功能

MinGW - 适用于 Windows 的极简 GNU
这个项目正在迁移到osdn.net/projects/mingw的过程中,你可以继续在那里关注我们。MinGW:GNU编译器集合(GCC)的本地Windows移植版本,可自由分发的导入库和用于构建本地Windows应用程序的头文件;包括对MSVC运行时的扩展,以支持C99功能。MinGW的所有软件都可以在64位Windows平台上运行。

SecLists
SecLists是最终安全测试人员的伙伴。它是一个包含各种类型列表的集合,这些列表在安全评估过程中经常使用,都在一个地方。SecLists通过方便地提供安全测试人员可能需要的所有列表,帮助提高安全测试的效率和生产力。列表类型包括用户名、密码、URL、模糊测试有效载荷、敏感数据模式、Web shell等等。测试人员只需将此存储库拉到新的测试机上,他就可以访问到所需的每种类型的列表。