zoukankan      html  css  js  c++  java
  • 代理模式八:装饰者模式

    简介

    装饰模式是在不必改变原类和使用继承的情况下,动态地扩展一个对象的功能。它是通过创建一个包装对象,也就是装饰来包裹真实的对象。

    使用场景

    通过继承的方式不现实的时候(可能由于排列组合产生类爆炸的问题)。

    代码

    • 顶级接口
    public interface ICoffee {
    
        void makeCoffee();
    
    }
    
    • 构建原始对象
    public class OriginalCoffee implements ICoffee {
        @Override
        public void makeCoffee() {
            System.out.print("原始咖啡制作");
        }
    }
    
    • 构建装饰者抽象基类,实现顶级接口
    public abstract class CoffeeConversion implements ICoffee {
    
        private ICoffee coffee;
    
        public CoffeeConversion(ICoffee coffee){
            this.coffee=coffee;
        }
    
        @Override
        public void makeCoffee() {
            coffee.makeCoffee();
        }
    }
    
    • 构建各种装饰者类,继承装饰者抽象基类(1)
    public class MilkCoffee extends CoffeeConversion{
        private ICoffee coffee;
    
        public MilkCoffee(ICoffee coffee) {
            super(coffee);
        }
    
        @Override
        public void makeCoffee() {
            super.makeCoffee();
            make();
        }
    
        public void make(){
            System.out.print("加奶");
        }
    }
    

    (2)

    public class SugarCoffee extends CoffeeConversion{
        public SugarCoffee(ICoffee coffee) {
            super(coffee);
        }
    
        @Override
        public void makeCoffee() {
            super.makeCoffee();
            make();
        }
    
        public void make(){
            System.out.print("加糖");
        }
    }
    
    • 测试类
    public class DecoratorTest {
    
        public static void main(String[] args) {
            //原味咖啡制作
            ICoffee coffee=new OriginalCoffee();
            coffee.makeCoffee();
            System.out.println("");
            //加奶咖啡
            coffee=new MilkCoffee(coffee);
            coffee.makeCoffee();
            System.out.println("");
            //先加奶后加糖
            coffee=new SugarCoffee(coffee);
            coffee.makeCoffee();
        }
    }
    
    输出数据:
    原始咖啡制作
    原始咖啡制作加奶
    原始咖啡制作加奶加糖
    

    总结

    装饰者模式使用很少,优点就是扩展性强,适用于排列组合需求

    Gitee地址

    https://gitee.com/zhuayng/foundation-study.git

    参考

    https://blog.csdn.net/ShuSheng0007/article/details/88780036

    XFS
  • 相关阅读:
    从string类的实现看C++类的四大函数 [写的很好]
    毕业5年决定你的命运
    git push 原因以及问题!
    poj 1195 Mobile phones 夜
    poj 2886 Who Gets the Most Candies 夜
    poj Asimple Problem With Integers 夜
    poj 2750 Potted Flower 夜
    poj 2528 Mayor's posters 夜
    poj 2777 Count Color 夜
    poj 2482 Stars in Your Window 夜
  • 原文地址:https://www.cnblogs.com/xiaofengshan/p/15167022.html
Copyright © 2011-2022 走看看