.NET Simple Factory Pattern Explanation
Introduction to the simple factory pattern:
The simple factory pattern is a creational pattern, also called the static factory method (Static Factory Method) pattern, but it is not one of the 23 GOF design patterns. The simple factory pattern uses a factory object to decide which product class instance to create. The simple factory pattern is the simplest and most practical pattern in the factory pattern family and can be understood as a special implementation of different factory patterns.
Structural pattern diagram:
Role classification:
Factory (Creator) role
The core of the simple factory pattern, it is responsible for implementing the internal logic of creating all instances. The method of creating a product class in the factory class can be directly called by the outside world to create the required product object.
Abstract Product Role
The parent class of all objects created by the simple factory pattern. It is responsible for describing the public interface common to all instances.
The Concrete Product role
is the creation target of the simple factory pattern. All objects created are instances of a specific class that plays this role.
Introducing the actual situation:
If there is a tenant management system, the tenant types in it are variable, and the rent calculation formula for each tenant type is different
The rent amount of type A tenant = number of days * unit price + Performance*0.005
B-type household rent amount = month*(monthly price+performance*0.001)
Analysis:
1. There is a common calculation method for stores. This is the behavior of physical stores, but their behavior is different. The method is different, so we abstract the store class, the code is as follows:
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace SimpleFactory.App.IFactroy { public interface Ishop { double Getrent(int days, double dayprice, double performance); } }
2. After abstracting the store, we need to create a specific product class, here is the specific type store, which implements the behavior method of the store . Create a store of type A
using SimpleFactory.App.IFactroy; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace SimpleFactory.App.product { //A类型的商店的创建 public class Ashop:Ishop { /// <summary> /// /// A类型商店租金额,天数*单价+绩效*0.005 /// </summary> /// <param name="days">天数</param> /// <param name="dayprice">每天单价</param> /// <param name="performance">日平均绩效</param> /// <returns></returns> public double Getrent(int days, double dayprice, double performance) { Console.WriteLine("A商店的租金算法"); return days * dayprice + performance * 0.01; } } }
3. Create a store of type B:
using SimpleFactory.App.IFactroy; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace SimpleFactory.App.product { /// <summary> /// B类型的商店的创建 /// </summary> public class Bshop:Ishop { /// <summary> /// B类型商店的租金=月份*(每月价格+performance*0.001) /// </summary> /// <param name="month">月数</param> /// <param name="monthprice">月单价</param> /// <param name="performance">月平均绩效</param> /// <returns></returns> public double Getrent(int month, double monthprice, double performance) { Console.WriteLine("B商店的租金算法"); return month * (monthprice + performance * 0.001); } } }
4. After creating a type store and implementing the method, think about how to create that kind of object under what circumstances, So the core part of the simple factory pattern: the factory class came out
using SimpleFactory.App.IFactroy; using SimpleFactory.App.product; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace SimpleFactory.App.factoryMethod { public class factorymethod { public Ishop CreateShow(string show) { switch (show.Trim().ToLower()) { case"ashop": return new Ashop(); case "bshop": return new Ashop(); default: throw new Exception("该商店不存在"); } } } }
5. Then based on the current store type, it is judged which algorithm should be used for this type of store:
using SimpleFactory.App.factoryMethod; using SimpleFactory.App.IFactroy; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace SimpleFactory.App { class Program { static void Main(string[] args) { Ishop As; factorymethod afm = new factorymethod(); As = afm.CreateShow("ashop"); //a 类型的某商店 double total = As.Getrent(30, 300, 2000); //30 天/100元 日平均绩效为2000 Console.WriteLine("该A类型商店的租金为:" + total); Console.WriteLine("============="); Ishop Bs; factorymethod bfm = new factorymethod(); Bs = bfm.CreateShow("bshop"); //b 类型的某商店 total = Bs.Getrent(3, 3000, 60000); //3 月/4000元 月平均绩效为60000 Console.WriteLine("该B类型商店的租金为:" + total); Console.ReadKey(); } } }
Here we have implemented the algorithm requirements for the two types of stores required by the customer, but as a good design architecture, we should also consider the subsequent demand changes. If the customer now adds C-type stores and D-type stores, Their algorithm requirements are different. At this time, we need to create C and D type stores, inherit the Ishop interface, and implement the methods inside. At the same time, we must continue to modify the factory class and add cases in switch to capture and create the corresponding stores. Object, once such a situation occurs, it is not conducive to the scalability of the program and the maintenance of the later project.
Advantages:
The simple factory pattern can decide which specific class of objects should be created based on the information given by the outside world. Through it, the outside world can get rid of the embarrassing situation of directly creating specific product objects.
The outside world is isolated from the specific class, and the coincidence is low.
Clearly distinguish their respective responsibilities and powers, which is conducive to the optimization of the entire software architecture.
Disadvantages:
The factory class concentrates the creation logic of all instances, which easily violates GRASPR's high cohesion responsibility allocation principle
Although the simple factory pattern can adapt to certain changes, the problems it can solve are far from the limited. The classes it can create can only be considered in advance. If you need to add a new class, you need to change the factory class.
How to solve the appeal situation that arises is worth thinking about and will be well solved in the next factory method pattern.
The above is the entire content of this article. I hope it will be helpful to everyone’s learning. I also hope that everyone will support the PHP Chinese website.

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



How to apply the simple factory pattern in PHP to improve code reusability. The simple factory pattern (SimpleFactoryPattern) is a commonly used design pattern that can provide a unified interface when creating objects so that different objects can be created according to different conditions. Example. This mode can effectively reduce the coupling of code and improve the maintainability and reusability of code. In PHP, we can use the simple factory pattern to optimize the structure and logic of the code. Understanding the simple factory pattern The simple factory pattern consists of three

How to implement object version control and management through the PHP object-oriented simple factory model. When developing large and complex PHP projects, version control and management are very important. Through appropriate design patterns, we can better manage and control the creation and use of objects, thereby improving the maintainability and scalability of the code. This article will introduce how to use the PHP object-oriented simple factory pattern to implement object version control and management. The simple factory pattern is a design pattern for creating classes that instantiates specified objects through a factory class

Explore Three Design Ideas of Java Factory Pattern Factory pattern is a commonly used design pattern for creating objects without specifying a specific class. In Java, the factory pattern can be implemented in many ways. This article will explore the implementation of three Java factory patterns based on different design ideas and give specific code examples. Simple Factory Pattern The simple factory pattern is the most basic factory pattern, which creates objects through a factory class. The factory class determines what kind of specific object should be created based on the client's request parameters. Below is a brief

Detailed explanation of the principles and applications of Java factory pattern Factory pattern is a commonly used design pattern, which is used to create objects and encapsulate the object creation process. There are many ways to implement the factory pattern in Java, the most common of which are the simple factory pattern, the factory method pattern and the abstract factory pattern. This article will introduce the principles and applications of these three factory patterns in detail, and give corresponding code examples. 1. Simple Factory Pattern The simple factory pattern is the simplest and most commonly used factory pattern. It uses a factory class to return different values based on the parameters passed in.

How to use the PHP object-oriented simple factory pattern to create testable object instances. The simple factory pattern is a commonly used software design pattern that helps us create different object instances based on different conditions. In PHP object-oriented programming, combining the simple factory pattern can improve the testability and maintainability of the code. In this article, we will learn how to create testable object instances using the object-oriented simple factory pattern in PHP. We will illustrate this process with a simple example. First, let's define an interface to represent the

How to apply the simple factory pattern in PHP to automate object creation. The simple factory pattern is a common design pattern that is used to create objects and abstracts the process of instantiating objects. In PHP, applying the simple factory pattern can help us decouple object creation and specific implementation, making the code more flexible and maintainable. In this article, we will use an example to illustrate how to apply the Simple Factory Pattern in PHP. Suppose we have an electronics store that sells mobile phones and televisions. We need to create photos based on user selections

How to achieve object polymorphism through the PHP object-oriented simple factory pattern. The simple factory pattern is a common design pattern that can create objects of different types through a common factory class and hide the object creation process. PHP object-oriented simple factory pattern can help us achieve object polymorphism. The simple factory pattern contains three basic roles: factory class, abstract class and concrete class. First we define an abstract class Animal, which contains an abstract method say(): abstractclas

How to realize unified entry and output of objects through PHP object-oriented simple factory pattern Introduction: In PHP development, the maintainability and scalability of the code can be improved by using object-oriented programming (Object-Oriented Programming, OOP). Object-oriented design pattern is a widely used method that can help us better organize and manage code. In this article, we will focus on how to achieve a unified entrance to objects by using the PHP object-oriented simple factory pattern.
