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
  • 相关阅读:
    Lucene学习总结之一:全文检索的基本原理
    Solr学习和总结(线下1)
    HBase学习系列
    Hadoop家族系列文章
    SQL on Hadoop系统的最新进展(1)
    【转】redis数据库入门教程(全面详细)+面试问题
    Redis(1.3)Redis的基本特性(事务、多数据库)
    (5.15)mysql高可用系列——mysql mha实践
    Redis(1.2)Redis的数据结构与基本操作
    mysql函数使用报错
  • 原文地址:https://www.cnblogs.com/alwaysdotnet/p/1205536.html
Copyright © 2011-2022 走看看