菜鸟教程 -- 学的不仅是技术,更是梦想!

设计模式
(追記) (追記ここまで)

装饰器模式

装饰器模式(Decorator Pattern)允许向一个现有的对象添加新的功能,同时又不改变其结构。这种类型的设计模式属于结构型模式,它是作为现有的类的一个包装。

装饰器模式通过将对象包装在装饰器类中,以便动态地修改其行为。

这种模式创建了一个装饰类,用来包装原有的类,并在保持类方法签名完整性的前提下,提供了额外的功能。

我们通过下面的实例来演示装饰器模式的用法。其中,我们将把一个形状装饰上不同的颜色,同时又不改变形状类。

概要

意图

动态地给一个对象添加额外的职责,同时不改变其结构。装饰器模式提供了一种灵活的替代继承方式来扩展功能。

主要解决的问题

  • 避免通过继承引入静态特征,特别是在子类数量急剧膨胀的情况下。
  • 允许在运行时动态地添加或修改对象的功能。

使用场景

  • 当需要在不增加大量子类的情况下扩展类的功能。
  • 当需要动态地添加或撤销对象的功能。

实现方式

  • 定义组件接口:创建一个接口,规定可以动态添加职责的对象的标准。
  • 创建具体组件:实现该接口的具体类,提供基本功能。
  • 创建抽象装饰者:实现同样的接口,持有一个组件接口的引用,可以在任何时候动态地添加功能。
  • 创建具体装饰者:扩展抽象装饰者,添加额外的职责。

关键代码

  • Component接口:定义了可以被装饰的对象的标准。
  • ConcreteComponent类:实现Component接口的具体类。
  • Decorator抽象类:实现Component接口,并包含一个Component接口的引用。
  • ConcreteDecorator类:扩展Decorator类,添加额外的功能。

应用实例

  1. 孙悟空的72变:孙悟空(ConcreteComponent)通过变化(Decorator)获得新的能力。
  2. 画框装饰画:一幅画(ConcreteComponent)可以通过添加玻璃(ConcreteDecorator)和画框(ConcreteDecorator)来增强其展示效果。

优点

  • 低耦合:装饰类和被装饰类可以独立变化,互不影响。
  • 灵活性:可以动态地添加或撤销功能。
  • 替代继承:提供了一种继承之外的扩展对象功能的方式。

缺点

  • 复杂性:多层装饰可能导致系统复杂性增加。

使用建议

  • 在需要动态扩展功能时,考虑使用装饰器模式。
  • 保持装饰者和具体组件的接口一致,以确保灵活性。

注意事项

  • 装饰器模式可以替代继承,但应谨慎使用,避免过度装饰导致系统复杂。

结构

装饰器模式包含以下几个核心角色:

  • 抽象组件(Component):定义了原始对象和装饰器对象的公共接口或抽象类,可以是具体组件类的父类或接口。
  • 具体组件(Concrete Component):是被装饰的原始对象,它定义了需要添加新功能的对象。
  • 抽象装饰器(Decorator):继承自抽象组件,它包含了一个抽象组件对象,并定义了与抽象组件相同的接口,同时可以通过组合方式持有其他装饰器对象。
  • 具体装饰器(Concrete Decorator):实现了抽象装饰器的接口,负责向抽象组件添加新的功能。具体装饰器通常会在调用原始对象的方法之前或之后执行自己的操作。

装饰器模式通过嵌套包装多个装饰器对象,可以实现多层次的功能增强。每个具体装饰器类都可以选择性地增加新的功能,同时保持对象接口的一致性。

实现

我们将创建一个 Shape 接口和实现了 Shape 接口的实体类。然后我们创建一个实现了 Shape 接口的抽象装饰类 ShapeDecorator,并把 Shape 对象作为它的实例变量。

RedShapeDecorator 是实现了 ShapeDecorator 的实体类。

DecoratorPatternDemo 类使用 RedShapeDecorator 来装饰 Shape 对象。

步骤 1

创建一个接口:

Shape.java

publicinterfaceShape{voiddraw(); }

步骤 2

创建实现接口的实体类。

Rectangle.java

publicclassRectangleimplementsShape{ @Overridepublicvoiddraw(){System.out.println("Shape: Rectangle"); }}

Circle.java

publicclassCircleimplementsShape{ @Overridepublicvoiddraw(){System.out.println("Shape: Circle"); }}

步骤 3

创建实现了 Shape 接口的抽象装饰类。

ShapeDecorator.java

publicabstractclassShapeDecoratorimplementsShape{protectedShapedecoratedShape; publicShapeDecorator(ShapedecoratedShape){this.decoratedShape = decoratedShape; }publicvoiddraw(){decoratedShape.draw(); }}

步骤 4

创建扩展了 ShapeDecorator 类的实体装饰类。

RedShapeDecorator.java

publicclassRedShapeDecoratorextendsShapeDecorator{publicRedShapeDecorator(ShapedecoratedShape){super(decoratedShape); } @Overridepublicvoiddraw(){decoratedShape.draw(); setRedBorder(decoratedShape); }privatevoidsetRedBorder(ShapedecoratedShape){System.out.println("Border Color: Red"); }}

步骤 5

使用 RedShapeDecorator 来装饰 Shape 对象。

DecoratorPatternDemo.java

publicclassDecoratorPatternDemo{publicstaticvoidmain(String[]args){Shapecircle = newCircle(); ShapeDecoratorredCircle = newRedShapeDecorator(newCircle()); ShapeDecoratorredRectangle = newRedShapeDecorator(newRectangle()); //Shape redCircle = new RedShapeDecorator(new Circle());//Shape redRectangle = new RedShapeDecorator(new Rectangle());System.out.println("Circle with normal border"); circle.draw(); System.out.println("\nCircle of red border"); redCircle.draw(); System.out.println("\nRectangle of red border"); redRectangle.draw(); }}

步骤 6

执行程序,输出结果:

Circle with normal border
Shape: Circle
Circle of red border
Shape: Circle
Border Color: Red
Rectangle of red border
Shape: Rectangle
Border Color: Red
AI 思考中...

9 篇笔记 写笔记

  1. #0

    周霆

    598***[email protected]

    141

    一个更易理解的实例:

    装饰模式为已有类动态附加额外的功能就像LOL、王者荣耀等类Dota游戏中,英雄升级一样。每次英雄升级都会附加一个额外技能点学习技能。具体的英雄就是ConcreteComponent,技能栏就是装饰器Decorator,每个技能就是ConcreteDecorator;

    //Component 英雄接口 
    public interface Hero {
     //学习技能
     void learnSkills();
    }
    //ConcreteComponent 具体英雄盲僧
    public class BlindMonk implements Hero {
     
     private String name;
     
     public BlindMonk(String name) {
     this.name = name;
     }
     @Override
     public void learnSkills() {
     System.out.println(name + "学习了以上技能!");
     }
    }
    //Decorator 技能栏
    public class Skills implements Hero{
     
     //持有一个英雄对象接口
     private Hero hero;
     
     public Skills(Hero hero) {
     this.hero = hero;
     }
     @Override
     public void learnSkills() {
     if(hero != null)
     hero.learnSkills();
     } 
    }
    //ConreteDecorator 技能:Q
    public class Skill_Q extends Skills{
     
     private String skillName;
     public Skill_Q(Hero hero,String skillName) {
     super(hero);
     this.skillName = skillName;
     }
     @Override
     public void learnSkills() {
     System.out.println("学习了技能Q:" +skillName);
     super.learnSkills();
     }
    }
    //ConreteDecorator 技能:W
    public class Skill_W extends Skills{
     private String skillName;
     public Skill_W(Hero hero,String skillName) {
     super(hero);
     this.skillName = skillName;
     }
     @Override
     public void learnSkills() {
     System.out.println("学习了技能W:" + skillName);
     super.learnSkills();
     }
    }
    //ConreteDecorator 技能:E
    public class Skill_E extends Skills{
     
     private String skillName;
     
     public Skill_E(Hero hero,String skillName) {
     super(hero);
     this.skillName = skillName;
     }
     @Override
     public void learnSkills() {
     System.out.println("学习了技能E:"+skillName);
     super.learnSkills();
     }
    }
    //ConreteDecorator 技能:R
    public class Skill_R extends Skills{ 
     
     private String skillName;
     
     public Skill_R(Hero hero,String skillName) {
     super(hero);
     this.skillName = skillName;
     }
     
     @Override
     public void learnSkills() {
     System.out.println("学习了技能R:" +skillName );
     super.learnSkills();
     }
    }
    //客户端:召唤师
    public class Player {
     public static void main(String[] args) {
     //选择英雄
     Hero hero = new BlindMonk("李青");
     
     Skills skills = new Skills(hero);
     Skills r = new Skill_R(skills,"猛龙摆尾");
     Skills e = new Skill_E(r,"天雷破/摧筋断骨");
     Skills w = new Skill_W(e,"金钟罩/铁布衫");
     Skills q = new Skill_Q(w,"天音波/回音击");
     //学习技能
     q.learnSkills();
     }
    }

    输出:

    学习了技能Q:天音波/回音击
    学习了技能W:金钟罩/铁布衫
    学习了技能E:天雷破/摧筋断骨
    学习了技能R:猛龙摆尾
    李青学习了以上技能!

    周霆

    598***[email protected]

    9年前 (2017年10月02日)
  2. #0

    该用户昵称违规

    815***[email protected]

    17

    游戏里英雄皮肤的实现 是不是也比较适合装饰器模式

    public interface Hero {
     public void init();
    }
    public class victor implements Hero {
     @Override
     public void init() {
     System.out.println("维克托:输出型英雄 武器:步枪");
     }
    }
    public abstract class HeroDecorator implements Hero {
     private Hero heroDecorator;
     public HeroDecorator(Hero heroDecorator) {
     this.heroDecorator = heroDecorator;
     }
     @Override
     public void init() {
     heroDecorator.init();
     }
    }
    public class GalacticWarriors extends HeroDecorator {
     private Hero heroDecorator;
     public GalacticWarriors(Hero heroDecorator) {
     super(heroDecorator);
     }
     @Override
     public void init() {
     super.init();
     setSkin();
     }
     private void setSkin() {
     System.out.println("皮肤:银河战士套装");
     }
    }
    public class DecoratorPatternDemo {
     public static void main(String[] args) {
     Hero victor = new victor();
     GalacticWarriors galacticWarriors = new GalacticWarriors(victor);
     galacticWarriors.init();
     }
    }

    该用户昵称违规

    815***[email protected]

    8年前 (2018年04月16日)
  3. #0

    郭为宇

    gos***[email protected]

    7

    《HeadFirst 设计模式》里的装饰器模式的代码。

    package HeadFirst设计模式.装饰者模式_星巴兹订单系统;
     
    /**
     *区别于Shape,Beverage采用抽象类
     *通常装饰者模式是采用抽象类,但是在Java中可以使用接口
     */
    public abstract class Beverage {
     public String description = "Unknown Beverage";
     
     public String getDescription() {
     return description;
     }
     
     public abstract double cost();
    }
    package HeadFirst设计模式.装饰者模式_星巴兹订单系统.被装饰者;
    import HeadFirst设计模式.装饰者模式_星巴兹订单系统.Beverage;
    /**
     *被装饰类继承Beverage抽象类,最终会通过装饰者动态添加上新的行为
     */
    public class DarkRoast extends Beverage {
     public DarkRoast() {
     description = "DarkRoast";
     }
     @Override 
     public double cost() {
     return 0.99;
     }
    }
    package HeadFirst设计模式.装饰者模式_星巴兹订单系统.装饰者;
    import HeadFirst设计模式.装饰者模式_星巴兹订单系统.Beverage;
    /**
     *这是继承Beverage的抽象装饰者,接下来所有具体的装饰者都要继承CondimentDecorator
     */
    public abstract class CondimentDecorator extends Beverage {
     /** 
     *所有的调料装饰者都必须重新实现该方法,因为调料的该方法应该得到扩充,方法实现不同于原来方法 
     */ 
     public abstract String getDescription();
    }
    package HeadFirst设计模式.装饰者模式_星巴兹订单系统.装饰者;
    import HeadFirst设计模式.装饰者模式_星巴兹订单系统.Beverage;
    /**
     *摩卡,是具体的装饰者
     *用一个实例变量记录饮料(被装饰者)
     *装饰者和被装饰者通过组合来增强功能,实现功能的扩展,用组合来替代继承
     */
    public class Mocha extends CondimentDecorator {
     Beverage beverage;
     public Mocha(Beverage beverage) {
     this.beverage = beverage;
     }
     @Override 
     public String getDescription() {
     return beverage.getDescription() + ", Mocha";
     }
     @Override 
     public double cost() {
     return 0.20 + beverage.cost();
     }
    }

    测试:

    package HeadFirst设计模式.装饰者模式_星巴兹订单系统;
    import HeadFirst设计模式.装饰者模式_星巴兹订单系统.被装饰者.DarkRoast;
    import HeadFirst设计模式.装饰者模式_星巴兹订单系统.装饰者.Mocha;
    public class TestStarbuzzCoffee {
     public static void main(String[] args) {
     Beverage beverage1 = new DarkRoast();
     beverage1 = new Mocha(beverage1);
     beverage1 = new Mocha(beverage1);
     System.out.println(beverage1.getDescription()+ " $" + beverage1.cost());
     }
    }

    输出:

    /Library/.../Java/设计模式/bin HeadFirst设计模式.装饰者模式_星巴兹订单系统.TestStarbuzzCoffee
    DarkRoast, Mocha, Mocha 1ドル.39
    Process finished with exit code 0

    郭为宇

    gos***[email protected]

    8年前 (2018年11月06日)
  4. #0

    这不是小明

    xia***[email protected]

    51

    复杂些的实例

    在《绝地求生:刺激战场》游戏里面我们都知道。

    • Kar 98K有5发子弹;
    • 装上弹匣后有10发子弹;
    • 装上4倍镜后可以进行4倍瞄准;
    • 装上8倍镜后可以进行4倍瞄准、8倍瞄准。

    枪具有开火功能:

    public interface Gun {
     /** * 开火直至打空子弹 */
     public void fire();
    }
    public class Kar98K implements Gun {
     @Override
     public void fire() {
     System.out.println("砰*5");
     }
    }

    装饰上弹匣变更枪开火功能:

    public abstract class AbstractMagazine implements Gun {
     private Gun gun;
     public AbstractMagazine(Gun gun) {
     this.gun = gun;
     }
     @Override
     public void fire() {
     gun.fire();
     }
    }
    public class Magazine extends AbstractMagazine {
     public Magazine(Gun gun) {
     super(gun);
     }
     @Override
     public void fire() {
     System.out.println("砰*10");
     }
    }
    测试:
    public class Demo {
     public static void main(String[] args) {
     System.out.println("[捡起一把98K]");
     Gun gun = new Kar98K();
     System.out.println("[开炮!]");
     gun.fire();
     System.out.println("[装饰上弹匣]");
     gun = new Magazine(gun);
     System.out.println("[开炮!]");
     gun.fire();
     }
    }

    输出:

    [捡起一把98K]
    [开炮!]
    砰*5
    [装饰上弹匣]
    [开炮!]
    砰*10

    现在我要装上4倍镜,使它具有4倍瞄准功能,这是枪支原本没有的功能。

    扩展枪支接口功能:

    public interface Aim4X extends Gun {
     public void aim4X();
    }
    public abstract class AbstractTelescope4X implements Aim4X {
     private Gun gun;
     public AbstractTelescope4X(Gun gun) {
     this.gun = gun;
     }
     @Override
     public void fire() {
     gun.fire();
     }
    }
    public class Telescope4X extends AbstractTelescope4X {
     public Telescope4X(Gun gun) {
     super(gun);
     }
     @Override
     public void aim4X() {
     System.out.println("已进入4倍瞄准模式");
     }
    }
    /** * 55式4倍镜 */
    public class Telescope4X55 extends AbstractTelescope4X {
     public Telescope4X55(Gun gun) {
     super(gun);
     }
     @Override
     public void aim4X() {
     System.out.println("4倍超级瞄准已部署");
     }
    }

    测试:

    public class Demo {
     public static void main(String[] args) {
     System.out.println("[捡起一把98K]");
     Gun gun = new Kar98K();
     System.out.println("[装饰上4倍镜]");
     Aim4X aim4X = new Telescope4X(gun);
     System.out.println("[4倍瞄准]");
     aim4X.aim4X();
     System.out.println("[开炮!]");
     aim4X.fire();
     System.out.println("[先装饰上弹匣]");
     gun = new Magazine(gun);
     System.out.println("[再装饰上4倍镜]");
     aim4X = new Telescope4X(gun);
     System.out.println("[4倍瞄准]");
     aim4X.aim4X();
     System.out.println("[开炮!]");
     aim4X.fire();
     System.out.println("[人体描边?换上我的55式4倍镜]");
     aim4X = new Telescope4X55(gun);
     System.out.println("[4倍瞄准]");
     aim4X.aim4X();
     System.out.println("[开炮!]");
     aim4X.fire();
     }
    }

    输出:

    [捡起一把98K]
    [装饰上4倍镜]
    [4倍瞄准]
    已进入4倍瞄准模式
    [开炮!]
    砰*5
    [先装饰上弹匣]
    [再装饰上4倍镜]
    [4倍瞄准]
    已进入4倍瞄准模式
    [开炮!]
    砰*10
    [人体描边?换上我的55式4倍镜]
    [4倍瞄准]
    4倍超级瞄准已部署
    [开炮!]
    砰*10

    现在我要装上8倍镜,它具有4倍瞄准功能,也具有8倍瞄准功能。

    扩展接口:

    public interface Aim8X extends Aim4X {
     public void aim8X();
    }
    public abstract class AbstractTelescope8X implements Aim8X {
     private Gun gun;
     public AbstractTelescope8X(Gun gun) {
     this.gun = gun;
     }
     @Override
     public void fire() {
     gun.fire();
     }
    }
    public class Telescope8X extends AbstractTelescope8X {
     public Telescope8X(Gun gun) {
     super(gun);
     }
     @Override
     public void aim8X() {
     System.out.println("进入8倍瞄准模式");
     }
     @Override
     public void aim4X() {
     System.out.println("进入4倍瞄准模式");
     }
    }

    测试:

    public class Demo {
     public static void main(String[] args) {
     System.out.println("[先装饰上弹匣]");
     gun = new Magazine(gun);
     System.out.println("[再装饰上8倍镜]");
     aim8X = new Telescope8X(gun);
     System.out.println("[8倍瞄准]");
     aim8X.aim8X();
     System.out.println("[敌人很近,换4倍]");
     aim8X.aim4X();
     System.out.println("[开炮!]");
     aim8X.fire();
     }
    }

    输出:

    [先装饰上弹匣]
    [再装饰上8倍镜]
    [8倍瞄准]
    进入8倍瞄准模式
    [敌人很近,换4倍]
    进入4倍瞄准模式 [开炮!] 砰*10

    这不是小明

    xia***[email protected]

    7年前 (2019年02月20日)
  5. #0

    Lonnie

    354***[email protected]

    2

    Swift 实现:

    protocol Shape {
     func draw()
    }
    protocol ShapeDecorator: Shape {
     var decoratedShape: Shape { get }
    }
    class Decorator {
     struct Rectangle: Shape {
     func draw() {
     print("Shape: Rectangle")
     }
     }
     struct Circle: Shape {
     func draw() {
     print("Shape: Circle")
     }
     }
     struct RedShapeDecorator: ShapeDecorator {
     var decoratedShape: Shape
     func draw() {
     decoratedShape.draw()
     setRedBorder(decoratedShape)
     }
     func setRedBorder(_ shape: Shape) {
     print("Border Color: Red")
     }
     }
     func execute() {
     let circle = Circle()
     let redCircle = RedShapeDecorator(decoratedShape: Circle())
     let redRectangle = RedShapeDecorator(decoratedShape: Rectangle())
     print("Circle with normal border:")
     circle.draw()
     print("Circle of red border")
     redCircle.draw()
     print("Circle of red rectangle")
     redRectangle.draw()
     }
    }

    Lonnie

    354***[email protected]

    7年前 (2019年12月11日)
  6. #0

    Siskin.xu

    sis***@sohu.com

    4

    Python 方式:

    # Decorator Pattern with Python Code
    from abc import abstractmethod,ABCMeta
    # 创建Shape接口
    class Shape(metaclass=ABCMeta):
     @abstractmethod
     def draw(self):
     pass
    # 实现Shape的实体类:Rectangle、Circle
    class Rectangle(Shape):
     def draw(self):
     print("Shape: Rectangle")
    class Circle(Shape):
     def draw(self):
     print("Shape: Circle")
    # 创建实现了Shape接口的抽象装饰类ShapeDecorator类
    class ShapeDecorator(Shape):
     _decoratedShape = None
     def __init__(self,inDecoratedShape):
     self._decoratedShape = inDecoratedShape
     def draw(self):
     self._decoratedShape.draw()
    # 创建扩展了ShapeDecorator类的实体装饰类对象
    class RedShapeDecorator(ShapeDecorator):
     def __init__(self,inDecoratedShape):
     ShapeDecorator.__init__(self,inDecoratedShape)
     def draw(self):
     self._decoratedShape.draw()
     self.setRedBorder(self._decoratedShape)
     def setRedBorder(self,inDecoratedShape):
     print("Border Color: Red")
    # 调用输出
    if __name__ == '__main__':
     aCircle = Circle()
     aRedCircle = RedShapeDecorator(Circle())
     aRedRectangle = RedShapeDecorator(Rectangle())
     print("Circle with normal border")
     aCircle.draw()
     print("\nCircle of red border")
     aRedCircle.draw()
     print("\nRectangle of red border")
     aRedRectangle.draw()

    Siskin.xu

    sis***@sohu.com

    6年前 (2020年03月03日)
  7. #0
    1

    C++语言

    /*
    练习:修饰模式。 
    业务:处理日志字符串,关键词屏蔽(业务上显然这个要优先处理)、日期添加
    */
    // 字符串父类
    class Text
    {
    public:
     Text() {};
     virtual void setText(string t) = 0;
     virtual string getText() = 0;
    };
    // 字符串实现
    class NormalText : public Text
    {
    private:
     string m_string;
    public:
     NormalText() {};
     virtual void setText(string t) {
     cout << "NormalText中存储字符串"<< endl;
     m_string = t;
     };
     string getText() {
     return m_string;
     };
    };
    // 字符串修饰器
    class TextDecorator : public Text
    {
    private:
     shared_ptr<Text> m_text;
    public:
     TextDecorator() {};
     void Decorate(shared_ptr<Text> & text) {
     m_text = text;
     }
     string getText() {
     return m_text->getText();
     };
     virtual void setText(string t) {
     m_text->setText(t);
     };
    };
    // 字符串修饰器具体:关键词屏蔽 
    class TextDecorator_blockword : public TextDecorator
    {
    private:
     string m_blockword; // 屏蔽词
    public:
     TextDecorator_blockword(string bw) :m_blockword(bw) {};
     void setText(string s) {
     cout << "屏蔽词语,屏蔽词为 "<< m_blockword << endl;
     // 循环找到每个屏蔽词,并替换为*
     for (std::size_t found = s.find(m_blockword); 
     found != std::string::npos; 
     found = s.find(m_blockword)) {
     s.replace(found, m_blockword.size(), m_blockword.size(), '*'); // 屏蔽词替换成*号
     }
     TextDecorator::setText(s);
     };
    };
    // 字符串修饰器具体:时间添加
    class TextDecorator_addtime : public TextDecorator
    {
    public:
     TextDecorator_addtime() {};
     void setText(string s) {
     cout << "添加时间戳" << endl;
     s = (string)"[2022年2月22日 22:22:22] " + s;
     TextDecorator::setText(s);
     };
    };
    // main 中执行
    void decorator_pattern_v2()
    {
     // 字符串
     string s("what a stupid son of a bitch. --- JoeBiden January,2022");
     // 原始字符创类
     shared_ptr<Text> text((Text*)(new NormalText()));
     // 创建修饰器 
     shared_ptr<Text> addtime((Text*)(new TextDecorator_addtime())); // 增加时间戳
     shared_ptr<Text> blk_bitch((Text*)(new TextDecorator_blockword("bitch"))); // 屏蔽 bitch
     shared_ptr<Text> blk_jb((Text*)(new TextDecorator_blockword("22"))); // 屏蔽 22
     // 加载修饰器
     dynamic_cast<TextDecorator_addtime*>(addtime.get())->Decorate(text);
     dynamic_cast<TextDecorator_blockword*>(blk_bitch.get())->Decorate(addtime);
     dynamic_cast<TextDecorator_blockword*>(blk_jb.get())->Decorate(blk_bitch);
     blk_jb->setText(s);
     cout << "原始字符串:" << s << endl;
     cout << "处理后字符串:" << text->getText() << endl;
    }

    控制台输出:

    屏蔽词语,屏蔽词为 22
    屏蔽词语,屏蔽词为 bitch
    添加时间戳
    NormalText中存储字符串
    原始字符串:what a stupid son of a bitch. --- JoeBiden January,2022
    处理后字符串:[2022年2月22日 22:22:22] what a stupid son of a *****. --- JoeBiden January,20**

    注意! 修饰器的顺序很重要,如果错误,则时间戳里的22字符创也会被屏蔽!

    4年前 (2022年02月01日)
  8. #0

    TooHandsomeException

    ywt***@163.com

    0

    老旧小区居民楼安装电梯:

    // BuildingInterface.java
    public interface BuildingInterface {
     void build();
    }
    // Building.java
    public class Building implements BuildingInterface {
     @Override
     public void build() {
     System.out.println("修建楼房");
     }
    }
    // BuildingDecorator.java
    public abstract class BuildingDecorator implements BuildingInterface {
     protected BuildingInterface building;
     public BuildingDecorator(BuildingInterface building) {
     this.building = building;
     }
     @Override
     public void build() {
     building.build();
     addDecorate();
     }
     protected abstract void addDecorate();
    }
    // Elevator.java
    public class Elevator extends BuildingDecorator {
     public Elevator(BuildingInterface building) {
     super(building);
     }
     @Override
     public void addDecorate() {
     System.out.println("加装电梯");
     }
    }
    // Demo.java
    public class Demo {
     public static void main(String[] args) {
     Building building = new Building();
     Elevator elevator = new Elevator();
     elevator.build();
     }
    }

    输出:

    修建楼房
    加装电梯

    TooHandsomeException

    ywt***@163.com

    4年前 (2022年09月14日)
  9. #0

    RUNOOB

    429***[email protected]

    0

    装饰器模式允许在运行时动态地添加和移除对象的功能,而无需修改其结构。它可以避免使用子类扩展导致的类爆炸问题,使得代码更加灵活可扩展。同时,装饰器模式也遵循开闭原则,可以方便地添加新的装饰器类,而不需要修改现有的代码。

    下面是一个简单的装饰器模式示例,假设有一个咖啡店,可以根据顾客的需求为咖啡添加额外的配料:

    // 抽象组件 - 咖啡
    interface Coffee {
     String getDescription();
     double getCost();
    }
    // 具体组件 - 普通咖啡
    class PlainCoffee implements Coffee {
     public String getDescription() {
     return "Plain Coffee";
     }
     public double getCost() {
     return 2.0;
     }
    }
    // 抽象装饰器 - 咖啡装饰器
    abstract class CoffeeDecorator implements Coffee {
     protected Coffee decoratedCoffee;
     public CoffeeDecorator(Coffee decoratedCoffee) {
     this.decoratedCoffee = decoratedCoffee;
     }
     public String getDescription() {
     return decoratedCoffee.getDescription();
     }
     public double getCost() {
     return decoratedCoffee.getCost();
     }
    }
    // 具体装饰器 - 牛奶装饰器
    class MilkDecorator extends CoffeeDecorator {
     public MilkDecorator(Coffee decoratedCoffee) {
     super(decoratedCoffee);
     }
     public String getDescription() {
     return super.getDescription() + ", Milk";
     }
     public double getCost() {
     return super.getCost() + 0.5;
     }
    }
    // 具体装饰器 - 糖浆装饰器
    class SyrupDecorator extends CoffeeDecorator {
     public SyrupDecorator(Coffee decoratedCoffee) {
     super(decoratedCoffee);
     }
     public String getDescription() {
     return super.getDescription() + ", Syrup";
     }
     public double getCost() {
     return super.getCost() + 0.8;
     }
    }
    // 客户端代码
    public class Main {
     public static void main(String[] args) {
     Coffee coffee = new PlainCoffee();
     System.out.println(coffee.getDescription() + ", Cost: " + coffee.getCost());
     Coffee milkCoffee = new MilkDecorator(coffee);
     System.out.println(milkCoffee.getDescription() + ", Cost: " + milkCoffee.getCost());
     Coffee syrupCoffee = new SyrupDecorator(coffee);
     System.out.println(syrupCoffee.getDescription() + ", Cost: " + syrupCoffee.getCost());
     Coffee milkSyrupCoffee = new SyrupDecorator(milkCoffee);
     System.out.println(milkSyrupCoffee.getDescription() + ", Cost: " + milkSyrupCoffee.getCost());
     }
    }

    在上面的示例中,我们定义了抽象组件接口 Coffee 和具体组件类 PlainCoffee。然后,我们定义了抽象装饰器类 CoffeeDecorator,以及具体装饰器类 MilkDecorator 和 SyrupDecorator。通过不断地嵌套装饰器对象,我们可以为咖啡添加不同的配料。

    RUNOOB

    429***[email protected]

    3年前 (2023年07月11日)

点我分享笔记

  • 昵称 (必填)
  • 邮箱 (必填)
  • 引用地址

AltStyle によって変換されたページ (->オリジナル) /