zoukankan      html  css  js  c++  java
  • 粗谈设计模式

    这两天在看设计模式,想在这边随便写点.
    模式一.装饰者模式 Decorate
    书中举的一个例子,就是卖咖啡的问题.
    首先coffee 有好多种,摩卡,蓝山等等.
    我们会定义一个基类class coffee
    {
        decimal cost();
    }
    然后派生两个类
    class mocha : coffee
    {
        decimal cost();
    }
    class blue : coffee
    {
        decimal cost();
    }

    这个时候顾客会有要求,我要加三份奶,两份糖,当然starbucks是免费的.
    很自然我们会定义两个类milk 和sugar
    class milk
    {
        decimal cost();{return 1.00;}
    }

    class sugar
    {
        decimal cost();{return 1.00;}
    }

    void main() //首先我们不考虑是mocha 还是blue,假定是mocha
    {
        decimal(Mocha mocha,int milknum,int sugarnum)
        {
            Sugar su = new Sugar();
            Milk mi = new Milk();
            return mocha.cost() + milknum * mi.cost() + sugarnum * su.cost();
        }
    }

    接下来是用装饰者模式来实现
    让每个辅料继承coffee
    class Milk :coffee
    {
        private coffee _coffee;
        public Milk(coffee coffee)

        {this._coffee = coffee;}
        decimal cost()
        {
            return 1.00 + _coffee.cost();
        }
    }
    sugar也是这样修改
    然后我们看main
    void main()
    {
        Coffee coffee = new Mocha();
        coffee = new sugar(coffee);
        coffee = new sugar(coffee);
        coffee = new sugar(coffee);
        coffee = new milk(coffee);
    coffee = new milk(coffee);
    cost(coffee);
    }
    decimal cost(coffee _coffee)
    {
        return _coffee.cost();
    }
    我发现在计算费用方面是方便了,但是对于,几份糖,几份奶还是不是很方便.

    Always.Net
  • 相关阅读:
    BZOJ5212 ZJOI2018历史(LCT)
    BZOJ5127 数据校验
    253. Meeting Rooms II
    311. Sparse Matrix Multiplication
    254. Factor Combinations
    250. Count Univalue Subtrees
    259. 3Sum Smaller
    156. Binary Tree Upside Down
    360. Sort Transformed Array
    348. Design Tic-Tac-Toe
  • 原文地址:https://www.cnblogs.com/alwaysdotnet/p/1205536.html
Copyright © 2011-2022 走看看