Design Patterns: simple factory models

Source: Internet
Author: User

Design Patterns: simple factory models

What is a simple factory model?

In terms of the design pattern type, the simple factory pattern belongs to the creation pattern, also known as the static factory method pattern, but does not belong to one of 23 gof design patterns. The simple factory mode is determined by a factory object to create a product instance. The simple factory model is the simplest and Practical Model in the factory model family. It can be understood as a special implementation of different factory models.

Roles and responsibilities

Factory (Creator) Role

The core of the simple factory mode is to implement the internal logic for creating all instances. The factory class can be directly called by the outside world to create the required product objects.

Abstract product (Product) Role

The parent class of all objects created in simple factory mode, which describes the common public interfaces of all instances.

Specific product (Concrete Product) Role

Is the creation target of the simple factory mode. All created objects are instances of a specific class that acts as this role.

Advantages and disadvantages

Advantages

The factory class is the key to the entire model. it contains the necessary logical judgment to determine the specific class object to be created based on the information given by the outside world. by using the factory class, the outside world can get rid of the embarrassing situation of directly creating specific product objects, and only need to be responsible for "consuming" objects. Without having to worry about how these objects are created and organized, they clearly define their respective responsibilities and rights, which is conducive to the optimization of the entire software architecture.

Disadvantages

Because the factory class integrates the creation logic of all instances, in violation of the High Cohesion responsibility allocation principle, all creation logic is centralized into a factory class; the class it can create can only be considered in advance, if you need to add a new class, you need to change the factory class.

When the number of product categories in the system increases, the requirements for the factory category to create different instances based on different conditions may arise. this kind of judgment on the condition is intertwined with the judgment on the specific product type. It is difficult to avoid the spread of module functions, which is very unfavorable for system maintenance and expansion.

Use Cases

The factory class is responsible for creating fewer objects;

The customer only knows the parameters passed into the factory class and does not care about how to create objects (logic;

Because simple factories are easy to violate the High Cohesion responsibility allocation principle, they are generally used only in simple cases. (For more information, see Baidu encyclopedia)

Code instance

In the following example, I want to simulate a user login function. In many systems, there are multiple users with different permissions, assume that the following Super User super user (s), Administrator admin (A), and Common User normal (n) exist in a system ), these three users must perform corresponding operations at different user levels during logon. Based on the above scenarios, we can use the following method to implement the simple factory model:

Step 1: create a public parent class for all user categories

 

 1 public class User { 2     private string _userType { get; set; } 3  4     public string UserType  5     { 6          get { return _userType; } 7          set { _userType = value; } 8     } 9 10     public virtual void ShowUser()11     {12     }13 }

This class defines the attributes of a user category and the virtual method of a real user category. Its subclass must implement this method.

Step 2 create a specific user class

Super User class:

1 class superuser: User {2 Public superuser () 3 {4 Base. usertype = "Super User"; 5} 6 Public override void showuser () 7 {8 console. writeline (base. usertype + "logged on"); 9} 10}

Administrator class:

1 class superuser: User {2 Public superuser () 3 {4 Base. usertype = "Administrator"; 5} 6 Public override void showuser () 7 {8 console. writeline (base. usertype + "logged on"); 9} 10}

Common User class:

1 class superuser: User {2 Public superuser () 3 {4 Base. usertype = "normal user"; 5} 6 Public override void showuser () 7 {8 console. writeline (base. usertype + "logged on"); 9} 10}

Step 3: Create a factory class and create different objects based on different input parameters.

 1 public class UserFactory { 2     public static User createUser(string userType) 3     { 4         User user = null; 5         switch (userType) 6         { 7             case "S": 8                 user = new SuperUser(); 9                 break;10             case "A":11                 user = new AdminUser();12                 break;13             case "N":14                 user = new NormalUser();15                 break;16             default:17                 break;18         }19     return user;20     }21 }

After completing the above work, we can use our class in the program. The program does not care how we create a specific user class, but explicitly passes the parameters of the class to be instantiated into the factory class, the factory class is responsible for calling the corresponding constructor to create a specific class, for example:

 1 class Program 2 { 3     static void Main(string[] args) 4     { 5         User user = null; 6         user = UserFactory.createUser("S"); 7         user.ShowUser(); 8         user = UserFactory.createUser("A"); 9         user.ShowUser();10         user = UserFactory.createUser("N");11         user.ShowUser();12         Console.ReadKey();13     }14 }

The userfactory class completely blocks the specific process of each user class. The output result is as follows:

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.