设计模式--装饰模式 Decorator Pattern

2019-10-21  本文已影响0人  慢慢1111

本文主要是记录《Head First 设计模式》知识,目的是检查自己学到的知识,同时方便我以后进行复习和浏览。

一、概述

1-1 定义

装饰模式 Decorator Pattern:The intend of this pattern is to add additional responsibilities dynamically to an object.
动态地给一个对象添加一些额外的职责。

该模式是一种结构型模式

1-2 模式结构

装饰模式包含如下角色:

图1 模式结构

二、举例:

星巴克更新订单系统,以合乎他们的饮料供应要求。购买咖啡时,可以加入各种调料,例如:蒸奶(Milk)、豆浆(Soy)、摩卡(Mocha)、覆盖奶泡(Whip)


图2 UML

代码
抽象构件:

/// <summary>
/// 抽象构件
/// </summary>
public abstract class Beverage
{
    public string description = "Unknown Beverage";
    public string getDescription()
    {
        return description;
    }

    public abstract double Cost();
}

具体构件:其中HouseBlend 、Espresso、DarkRoast、Decaf代码相似,此处只写一处

/// <summary>
/// 具体构件
/// </summary>
class HouseBlend : Beverage
{
    public HouseBlend()
    {
        description = "HouseBlend";
    }

    public override double Cost()
    {
        return 1.99;
    }
}

抽象装饰类

/// <summary>
/// 抽象装饰类
/// </summary>
public abstract class CondimentDecorator:Beverage
{
    public abstract string getDescription();
}

具体抽象类:其中Soy、Milk、Mocha、Whip代码相似,此处只写一个

/// <summary>
/// 豆浆
/// </summary>
class Soy : CondimentDecorator
{
    Beverage beverage;
    public Soy(Beverage beverage)
    {
        this.beverage = beverage;
    }
    public override double Cost()
    {
        return 0.20 + beverage.Cost();
    }
    public override string getDescription()
    {
        return beverage.getDescription() + ",Soy";
    }
}

测试程序

class Program
{
    static void Main(string[] args)
    {
        //要一杯HouseBlend
        Beverage beverage = new HouseBlend();
        Console.WriteLine(beverage.getDescription() + "$" + beverage.Cost());


        Beverage beverage1 = new DarkRoast();
        beverage1 = new Mocha(beverage1);
        beverage1 = new Mocha(beverage1);
        beverage1 = new Whip(beverage1);
        Console.WriteLine(beverage1.getDescription() + "$" + beverage1.Cost());
        Console.ReadKey();
    }
}

运行结果


图3 运行结果

三 总结

3-1 模式优缺点

优点

3-2 适合场景

总结

上一篇下一篇

猜你喜欢

热点阅读