设计模式-装饰器模式

装饰器模式

简介

将对象放入特殊的装饰对象中从而使其获得新的行为

应用

类图

在这里插入图片描述

代码

  1. 问题:加入开了一个咖啡店,创建咖啡时可能往咖啡中加入不同类型的添加剂,例如牛奶,焦糖等,此时应该如何设计类

    • 解决:将对应添加剂类型组合成新的子类,例如牛奶咖啡,焦糖咖啡,牛奶焦糖咖啡等
  2. 问题:如果有新的添加剂怎么办?如果添加剂过多可能造成类数量爆炸

    • 解决:采用装饰模式,将添加剂作为装饰器装饰咖啡
    // 咖啡类对应类图上最顶层的模板类
    public abstract class Coffee {
    	String description;
    	
    	public Coffee() {
    	}
    	
    	public Coffee(String description) {
    		this.description = description;
    	}
    	
    	void getDescription() {
    		System.out.println(description);
    	};
    }
    // 具体的咖啡类,对应被装饰的对象
    public class CoffeeA extends Coffee{
    	public CoffeeA(String description) {
    		super(description);
    	}
    
    	String description = "CoffeeA";
    }
    // 装饰器超类,对应所有装饰器父类
    public class CoffeeDecorator extends Coffee{
    	Coffee coffee = null;
    	
    	CoffeeDecorator(Coffee _coffee){
    		this.coffee = _coffee;
    	}
    	
    	void getDescription() {
    		this.coffee.getDescription();
    	};
    }
    // 装饰器1
    public class CoffeeDecorator1 extends CoffeeDecorator{
    	Coffee coffee = null;
    	
    	CoffeeDecorator1(Coffee _coffee){
    		super(_coffee);
    	}
    	
    	void getDescription() {
    		method1();
    		super.getDescription();
    	};
    	
    	void method1() {
    		System.out.println("咖啡中添加标号为1的添加剂");
    	}
    }
    // 装饰器2
    public class CoffeeDecorator2 extends CoffeeDecorator{
    	Coffee coffee = null;
    	
    	CoffeeDecorator2(Coffee _coffee){
    		super(_coffee);
    	}
    	
    	void getDescription() {
    		method2();
    		super.getDescription();
    	};
    	
    	void method2() {
    		System.out.println("咖啡中添加标号为2的添加剂");
    	}
    }
    // 客户端
    
    public class Client {
    	public static void main(String[] args) {
    		Coffee coffeeA = new CoffeeA("咖啡A");
    		coffeeA = new CoffeeDecorator1(coffeeA);
    		coffeeA = new CoffeeDecorator2(coffeeA);
    		
    		coffeeA.getDescription();
    		
    		
    	}
    }
    
    

    结果

    咖啡中添加标号为2的添加剂
    咖啡中添加标号为1的添加剂
    咖啡A

    可以看到咖啡A 已经被两个添加剂修饰

引用

  1. https://refactoringguru.cn/design-patterns/decorator/java/example

  2. Head First 设计模式

  • 3
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值