Java 设计模式之装饰模式,Java 装饰模式
================================
?Copyright 蕃薯耀 2021-07-01
https://www.cnblogs.com/fanshuyao/
一、Java 装饰模式
1、接口(Component,抽象构件)
public interface FastFood { /** * 花费金额 * @return */ public double cost(); /** * 描述 * @return */ public String desc(); }
2、具体的实现类(ConcreteComponent,具体构件,或者基础构件)
/** * 炒饭,具体的类 * */ public class FriedRice implements FastFood{ @Override public double cost() { return 10; } @Override public String desc() { return "炒饭"; } }
3、装饰抽象类(Decorator,装饰角色)
/** * 配菜抽象类 * */ public abstract class SideDish implements FastFood{ //快餐类 private FastFood fastFood; public SideDish(FastFood fastFood) { this.fastFood = fastFood; } @Override public double cost() { return fastFood.cost(); } @Override public String desc() { return fastFood.desc(); } }
4、装饰类子类(ConcreteDecorator,具体装饰角色)
public class SideDishEgg extends SideDish { public SideDishEgg(FastFood fastFood) { super(fastFood); } @Override public double cost() { return 1 + super.cost(); } @Override public String desc() { return "鸡蛋" + " + " + super.desc(); } }
5、装饰类子类2(ConcreteDecorator,具体装饰角色)
public class SideDishPork extends SideDish { public SideDishPork(FastFood fastFood) { super(fastFood); } @Override public double cost() { return 2 + super.cost(); } @Override public String desc() { return "猪肉" + " + " + super.desc(); } }
6、测试结果
炒饭 10.0 -------------------------------------------------- 鸡蛋 + 炒饭 11.0 -------------------------------------------------- 鸡蛋 + 鸡蛋 + 炒饭 12.0 -------------------------------------------------- 猪肉 + 鸡蛋 + 鸡蛋 + 炒饭 14.0
7、装饰器模式在Java I/O系统中的实现
8、Java 设计模式之代理模式,Java 静态代理,Java 动态代理
https://www.cnblogs.com/fanshuyao/p/14911666.html
9、java装饰模式和代理模式的区别
代理模式:
侧重于不能直接访问一个对象,只能通过代理来间接访问,起到保存对象的作用。
装饰器模式:
是因为没法在编译器就确定一个对象的功能,需要运行时动态的给对象添加职责,所以只能把对象的功能拆成一个个的小部分,动态组装。
装饰模式可以装了又装,层层包裹; 代理一般不会代了又代。
(时间宝贵,分享不易,捐赠回馈,^_^)
================================
?Copyright 蕃薯耀 2021-07-01
https://www.cnblogs.com/fanshuyao/
原文:https://www.cnblogs.com/fanshuyao/p/14957423.html