Home Backend Development C#.Net Tutorial In-depth understanding of the strategy pattern of C# design patterns and role-specific case sharing

In-depth understanding of the strategy pattern of C# design patterns and role-specific case sharing

Jul 28, 2018 am 11:57 AM
c# Design Patterns

Strategy Pattern

The strategy pattern is a behavioral pattern. It defines a series of algorithms, encapsulates each algorithm, and makes them Can be interchanged, allowing the algorithm to change independently of the client using it.

Using the strategy pattern can separate behavior and environment. The environment class is responsible for maintaining and querying the behavior class, and various algorithms are provided in the specific strategy class.

Role:

1. Abstract strategy (Strategy)

This is an abstract role, usually implemented by an interface or abstract class. This role gives all the interfaces required by concrete strategy classes;

2. Concrete Strategy

A concrete strategy class that implements an abstract strategy and packages related algorithms or behaviors;

3. Environment class (Context)

holds a reference to the Strategy class and can select the corresponding strategy for the instance based on logic.

Example:

In-depth understanding of the strategy pattern of C# design patterns and role-specific case sharing

The namespace StrategyPattern contains the strategy base class Tax and its 8 implementation classes, and the Context environment class holds There are strategy base classes. This example provides an elegant way to calculate personal income tax.

C# Development Notes 04-How to use C# to elegantly calculate personal income tax?

1

namespace StragetyPattern

Copy after login

1

2

3

4

5

6

7

8

9

10

11

public abstract class Tax {

 

    protected decimal TaxRate = 0;

 

    protected decimal QuickDeduction = 0;

 

    public virtual decimal Calculate(decimal income) {

        return income * TaxRate - QuickDeduction;

    }

 

}

Copy after login

The strategy base class Tax represents personal income tax, TaxRate is the tax rate, QuickDeduction is the quick calculation deduction, and Calculate calculates the personal income tax of the corresponding income.

1

2

3

4

5

6

7

8

public class Level0 : Tax {

 

    public Level0() {

        TaxRate = 0.00m;

        QuickDeduction = 0;

    }

 

}

Copy after login

Level 0 personal income tax ladder represents the initial status of personal income tax.

1

2

3

4

5

6

7

8

public class Level1 : Tax {

 

    public Level1() {

        TaxRate = 0.03m;

        QuickDeduction = 0;

    }

 

}

Copy after login

Level 1 personal income tax ladder.

1

2

3

4

5

6

7

8

public class Level2 : Tax {

 

    public Level2() {

        TaxRate = 0.10m;

        QuickDeduction = 105;

    }

 

}

Copy after login

Level 2 personal income tax ladder.

1

2

3

4

5

6

7

8

public class Level3 : Tax {

 

    public Level3() {

        TaxRate = 0.20m;

        QuickDeduction = 555;

    }

 

}

Copy after login

3 levels of personal income tax ladder.

1

2

3

4

5

6

7

8

public class Level4 : Tax {

 

    public Level4() {

        TaxRate = 0.25m;

        QuickDeduction = 1005;

    }

 

}

Copy after login

4 levels of personal income tax ladder.

1

2

3

4

5

6

7

8

public class Level5 : Tax {

 

    public Level5() {

        TaxRate = 0.30m;

        QuickDeduction = 2755;

    }

 

}

Copy after login

5-level personal income tax ladder.

1

2

3

4

5

6

7

8

public class Level6 : Tax {

 

    public Level6() {

        TaxRate = 0.35m;

        QuickDeduction = 5505;

    }

 

}

Copy after login

6-level personal income tax ladder.

1

2

3

4

5

6

7

8

public class Level7 : Tax {

 

    public Level7() {

        TaxRate = 0.45m;

        QuickDeduction = 13505;

    }

 

}

Copy after login

7 levels of personal income tax ladder.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

public class Context {

 

    private Tax _tax = null;

 

    private const decimal EXEMPTION_VALUE = 3500m;

 

    private List<decimal> _taxLevel = new List<decimal>{

        0,

        1500,

        4500,

        9000,

        35000,

        55000,

        80000,

        decimal.MaxValue

    };

 

    private List<Type> _levels = new List<Type>();

 

    private void GetLevels() {

        _levels = AppDomain.CurrentDomain.GetAssemblies()

                           .SelectMany(tp => tp.GetTypes()

                           .Where(t => t.BaseType == typeof(Tax)))

                           .ToList();

    }

 

    public Context() {

        GetLevels();

    }

 

    public Context Calculate(decimal income) {

        _tax = new Level0();

        var result = income - EXEMPTION_VALUE;

        for(int i = 1; i <= _taxLevel.Count - 1; i++) {

            if(result > _taxLevel[i - 1] && result <= _taxLevel[i]) {

                _tax = (Tax)Activator.CreateInstance(_levels[i]);

            }

        }

        Console.WriteLine($"Income = {income}," + $"tax = {_tax.Calculate(result)}!");

        return this;

    }

 

}

Copy after login

Environment class Context, first need to maintain a reference to Tax, EXEMPTION_VALUE represents the exemption amount (3500 yuan is used in this example), and then select the corresponding Tax implementation class through reflection and some techniques to calculate the individuals of the corresponding ladder Income Tax.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

public class Program {

 

    private static Context _context = new Context();

 

    public static void Main(string[] args) {

        _context.Calculate(2500.00m)

                .Calculate(4900.00m)

                .Calculate(5500.00m)

                .Calculate(7000.00m)

                .Calculate(10000.00m)

                .Calculate(16000.00m)

                .Calculate(43000.00m)

                .Calculate(70000.00m)

                .Calculate(100000.00m)

                .Calculate(4500.00m)

                .Calculate(1986.00m);

 

        Console.ReadKey();

    }

 

}

Copy after login

The above is the caller's code, Calculate has been specially processed to support method chaining. The following is the output result of this case:

1

2

3

4

5

6

7

8

9

10

11

Income = 2500.00,tax = 0.0000!

Income = 4900.00,tax = 42.0000!

Income = 5500.00,tax = 95.0000!

Income = 7000.00,tax = 245.0000!

Income = 10000.00,tax = 745.0000!

Income = 16000.00,tax = 2120.0000!

Income = 43000.00,tax = 9095.0000!

Income = 70000.00,tax = 17770.0000!

Income = 100000.00,tax = 29920.0000!

Income = 4500.00,tax = 30.0000!

Income = 1986.00,tax = 0.0000!

Copy after login

Advantages:

1. The hierarchical structure of the strategy class defines an algorithm or behavior family. Proper use of inheritance can convert public Move the code into the parent class to avoid duplication of code;
2. Inheritance can handle a variety of algorithms or behaviors and avoid using multiple conditional transfer statements.

Disadvantages:

1. The client must know all the policy classes and decide which one to use;
2. The strategy mode causes a lot of problems Strategy class, causing "subclass explosion".

Usage scenarios:

1. If there are many classes in a system and the difference between them is only their behavior, then the strategy pattern can be used to dynamically Let an object choose one behavior among many behaviors;
2. A system needs to dynamically choose one of several algorithms.

Related articles:

Writing PHP Extension using C/C

##[c# tutorial]C# data type

Related videos:

What is design pattern-php advanced design pattern video tutorial

The above is the detailed content of In-depth understanding of the strategy pattern of C# design patterns and role-specific case sharing. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Active Directory with C# Active Directory with C# Sep 03, 2024 pm 03:33 PM

Guide to Active Directory with C#. Here we discuss the introduction and how Active Directory works in C# along with the syntax and example.

Random Number Generator in C# Random Number Generator in C# Sep 03, 2024 pm 03:34 PM

Guide to Random Number Generator in C#. Here we discuss how Random Number Generator work, concept of pseudo-random and secure numbers.

Access Modifiers in C# Access Modifiers in C# Sep 03, 2024 pm 03:24 PM

Guide to the Access Modifiers in C#. We have discussed the Introduction Types of Access Modifiers in C# along with examples and outputs.

C# Data Grid View C# Data Grid View Sep 03, 2024 pm 03:32 PM

Guide to C# Data Grid View. Here we discuss the examples of how a data grid view can be loaded and exported from the SQL database or an excel file.

C# Serialization C# Serialization Sep 03, 2024 pm 03:30 PM

Guide to C# Serialization. Here we discuss the introduction, steps of C# serialization object, working, and example respectively.

Patterns in C# Patterns in C# Sep 03, 2024 pm 03:33 PM

Guide to Patterns in C#. Here we discuss the introduction and top 3 types of Patterns in C# along with its examples and code implementation.

Prime Numbers in C# Prime Numbers in C# Sep 03, 2024 pm 03:35 PM

Guide to Prime Numbers in C#. Here we discuss the introduction and examples of prime numbers in c# along with code implementation.

Factorial in C# Factorial in C# Sep 03, 2024 pm 03:34 PM

Guide to Factorial in C#. Here we discuss the introduction to factorial in c# along with different examples and code implementation.

See all articles