Java 装饰者模式
装饰者模式可以给一个对象添加一些额外的职责,单从增加功能方面来说,装饰者模式比生成子类更加灵活。该模式采用对客户端透明的方式扩展对象的功能。
适用环境:
(1)在不影响其他对象的情况下,动态、透明地给单个对象添加职责。
(2)处理那些可以撤销的职责。
(3)当不能使用子类的方法进行扩充时。
装饰者模式在学习IO流的过程中,就接触过,例如:
//创建字节流 InputStream in = new FileInputStream("C:/test/hello.txt"); //在字节流的技术上加入缓冲 BufferedInputStream bis = new BufferedInputStream(in); //在缓冲的基础上加入打印流 PrintStream ps = new PrintStream(bis);
装饰者模式包括四个部分:
(1)Componnet(被装饰对象基类)
定义对象的接口,动态给对象添加职责
(2)ConcreteComponnet(具体被装饰对象)
定义具体的对象,Decorator可以动态给它添加职责
(3)Decorator(装饰抽象类)
维护指向Component实例的引用,定义与Component一致的接口
(4)ConcreteDecorator(具体装饰者)
具体的装饰对象,给内部持有的具体被装饰类对象添加具体的职责
代码示例:
Componnet(被装饰对象基类)
public interface Drink { public int price(); public String decription(); }
ConcreteComponnet(具体被装饰对象)
public class SoyabeanDrink implements Drink { @Override public int price() { return 10; } @Override public String decription() { return "纯豆浆"; } }
Decorator(装饰抽象类)
public class Decorator implements Drink{ private Drink drink; public Decorator(Drink drink){ this.drink = drink; } @Override public int price() { return drink.price(); } @Override public String decription() { return drink.decription(); } }
ConcreteDecorator(具体装饰者)
public class SugarSoyabeanDrink extends Decorator{ public SugarSoyabeanDrink(Drink drink) { super(drink); } @Override public int price() { return super.price()+1; } @Override public String decription() { return super.decription()+"+糖"; } } class MilkSoyabeanDrink extends Decorator{ public MilkSoyabeanDrink(Drink drink) { super(drink); } @Override public int price() { return super.price()+2; } @Override public String decription() { return super.decription()+"+牛奶"; } } class CaffeSoyabeanDrink extends Decorator { public CaffeSoyabeanDrink(Drink drink) { super(drink); } @Override public int price() { return super.price()+3; } @Override public String decription() { return super.decription()+"+咖啡"; } }
测试类
public class TestDecoration { public static void main(String[] args) { Drink drink = new SoyabeanDrink(); SugarSoyabeanDrink sugar = new SugarSoyabeanDrink(drink); MilkSoyabeanDrink milk = new MilkSoyabeanDrink(sugar); CaffeSoyabeanDrink caffe = new CaffeSoyabeanDrink(milk); int price = caffe.price(); String description = caffe.decription(); System.out.println(price); //16 System.out.println(description); //纯豆浆+糖+牛奶+咖啡 } }
本文来自博客园,作者:藤原豆腐渣渣,转载请注明原文链接:https://www.cnblogs.com/javafufeng/p/16406912.html
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 使用C#创建一个MCP客户端
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· ollama系列1:轻松3步本地部署deepseek,普通电脑可用
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 按钮权限的设计及实现