Design Pattern Learning---strategy mode

Source: Internet
Author: User

Recently, looking at "Head First design mode" This book, I would like to learn from the record to deepen understanding, there must be many shortcomings in the text, please the predecessors pointed out.

What is design mode

The design pattern is not a tool in a development language, but a manifestation of our handling of problems, we always use design patterns in our work, we encounter various problems when we work, and then we think and summarize. Get a set of experience in dealing with problems, perhaps we do not know what is the design pattern, But for a problem we have a solution, and then by watching it people's code will find others dealing with this kind of problem with their own summary of the same, in fact, the design pattern is so, it is the predecessors through a lot of experience summed up a set of programming ideas, and then through the record and share, So there are23 design patterns in the Bible that are now programmed-----. That is, design patterns are not mysterious, but they are so important.

Note : The problem described here is the problem with the design of the code, not the functional requirements, such as the tight coupling of the code

Introduction to Policy mode

Here's the first design pattern: policy mode, which is an extremely simple pattern, but also an extremely common pattern, the following is an extremely simple example of the policy pattern
Now to design a promotional function for a shopping mall, but now do not know the specific promotional needs, we just need to design the promotion requirements, and then in the late to add specific promotional strategies, so we quickly completed the first version of this class

// 商品类class Goods{     // 商品名称     public string GoodsName { get; set; }     // 商品价格     public decimal GoodsPrice { get; set; }     // 促销方法     public void Discount()     {        Console.WriteLine("这是促销方法,目前无促销");     }}   

Note: This is a simple example, just to illustrate the strategy pattern.

This simple type is the first version of the product promotion function, but there is a huge problem here is that the promotion strategy changes so that we have to change their code. This is in line with our design philosophy, and we observe that the promotion is a variable part of this function, And we can separate the mutable parts, now let's change the code.

    // 商品类    class Goods    {        //促销类引用        public DiscountStrategyClass DiscountStrategyClass { get; set; }        // 商品名称        public string GoodsName { get; set; }        // 商品价格        public decimal GoodsPrice { get; set; }        // 促销方法        public void Discount()        {            //调用促销类的促销方法            DiscountStrategyClass.Discount();            //Console.WriteLine("这是促销方法,目前无促销");        }    }    // 促销类    class DiscountStrategyClass    {        // 促销方法        public void Discount()        {            Console.WriteLine("这是促销方法,目前无促销");        }    }

The above is the code that we separated the promotion method, I created a promotion class, and then in the product class to create a promotion class reference and in the promotion method to invoke the promotion of promotional methods, and then we actually can think of the next step, that is, to create an abstract promotional class, and then sub-class implementation, and agreed to their own promotion strategy, and commodity class simply declare and invoke the abstract promotion of promotional methods can be,

    // 商品类    class Goods    {        //促销接口引用        public IDiscountStrategy DiscountStrategy { get; set; }        // 商品名称        public string GoodsName { get; set; }        // 商品价格        public decimal GoodsPrice { get; set; }        // 促销方法        public void Discount()        {            //调用促销类的促销方法            DiscountStrategy.Discount();            //Console.WriteLine("这是促销方法,目前无促销");        }    }    // 促销类    interface IDiscountStrategy    {        // 定义促销方法        void Discount();    }    //八折折扣    class EightyPercentDS : IDiscountStrategy    {        public void Discount()        {            Console.WriteLine("这是促销方法,我打八折");        }    }    //七折折扣    class SevenPercentDS : IDiscountStrategy    {        public void Discount()        {            Console.WriteLine("这是促销方法,我打八折");        }    }

This small promotional feature is done, and we can feel that this is always used when writing code
Here you can see the two benefits of the strategy model

  1. You can add a new policy without changing the current structure
  2. Can dynamically change policies at run time

The strategy model embodies two principles:

  1. Find out where the program may need to be changed, and separate it so that the rest of it will not be affected by it.
  2. Multi-use combination, less inheritance

The strategy model emphasizes the combination, that is, there is a (has-a), but here is not a very good embodiment, in the decorator model is more good to reflect
We also have to adhere to this rule when designing code to make the system more resilient.

Policy Mode Structure UML

Here is a UML diagram of this simple policy pattern

In the project, however, the abstraction of the Environment role class (current goods) into an abstract class, or a UML diagram, is sometimes abstracted.

Such a UML can be imagined as the goods class into an abstract class, and then declare its subclasses, such as Computergoods (TV), Bookgoods (books), and then use the inherited characteristics to liberate the implementation, which is what we often say面对接口编程

Note: The face of interface programming is not the face of interface programming, but the face of super-class programming

Policy Mode definition

Define an algorithm family, encapsulate them separately, and let them replace each other, this pattern allows the algorithm to change independently of the client using the algorithm

Design Pattern Learning---strategy mode

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.