设计模式之“策略模式”

策略模式:
策略模式定义了一系列算法,把它们一个个封装起来,并且使它们可相互替换。该模式可使得算法能独立于使用它的客户而变化。

通用类图:

实例:

商品折扣计算

 class Program
    {
        static void Main(string[] args)
        {
            ShopCart sc = new ShopCart(new ProudctA());
            sc.doSomthing();
            sc = new ShopCart(new ProudctB());
            sc.doSomthing();
        }
    }
    public class ShopCart {
        public IStrategy strategr;
        public ShopCart(IStrategy strategr) {
            this.strategr = strategr;
        }
        public void doSomthing()
        {
            this.strategr.compute();
        }
    }
    public interface IStrategy
    {

         void compute();
    }
    public class ProudctA : IStrategy {

        public void compute()
        {
            Console.WriteLine("商品折扣价100");
        }
    }
    public class ProudctB: IStrategy
    {

        public void compute()
        {
            Console.WriteLine("商品折扣价200");
        }
    }

 

posted @ 2013-07-17 21:57  走到天亮  阅读(301)  评论(0编辑  收藏  举报