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.

C# and .NET provide powerful features and an efficient development environment. 1) C# is a modern, object-oriented programming language that combines the power of C and the simplicity of Java. 2) The .NET framework is a platform for building and running applications, supporting multiple programming languages. 3) Classes and objects in C# are the core of object-oriented programming. Classes define data and behaviors, and objects are instances of classes. 4) The garbage collection mechanism of .NET automatically manages memory to simplify the work of developers. 5) C# and .NET provide powerful file operation functions, supporting synchronous and asynchronous programming. 6) Common errors can be solved through debugger, logging and exception handling. 7) Performance optimization and best practices include using StringBuild

.NETFramework is a cross-language, cross-platform development platform that provides a consistent programming model and a powerful runtime environment. 1) It consists of CLR and FCL, which manages memory and threads, and FCL provides pre-built functions. 2) Examples of usage include reading files and LINQ queries. 3) Common errors involve unhandled exceptions and memory leaks, and need to be resolved using debugging tools. 4) Performance optimization can be achieved through asynchronous programming and caching, and maintaining code readability and maintainability is the key.

Reasons for C#.NET to remain lasting attractive include its excellent performance, rich ecosystem, strong community support and cross-platform development capabilities. 1) Excellent performance and is suitable for enterprise-level application and game development; 2) The .NET framework provides a wide range of class libraries and tools to support a variety of development fields; 3) It has an active developer community and rich learning resources; 4) .NETCore realizes cross-platform development and expands application scenarios.

Design patterns in C#.NET include Singleton patterns and dependency injection. 1.Singleton mode ensures that there is only one instance of the class, which is suitable for scenarios where global access points are required, but attention should be paid to thread safety and abuse issues. 2. Dependency injection improves code flexibility and testability by injecting dependencies. It is often used for constructor injection, but it is necessary to avoid excessive use to increase complexity.

C#.NET is widely used in the modern world in the fields of game development, financial services, the Internet of Things and cloud computing. 1) In game development, use C# to program through the Unity engine. 2) In the field of financial services, C#.NET is used to develop high-performance trading systems and data analysis tools. 3) In terms of IoT and cloud computing, C#.NET provides support through Azure services to develop device control logic and data processing.

.NETFrameworkisWindows-centric,while.NETCore/5/6supportscross-platformdevelopment.1).NETFramework,since2002,isidealforWindowsapplicationsbutlimitedincross-platformcapabilities.2).NETCore,from2016,anditsevolutions(.NET5/6)offerbetterperformance,cross-

The C#.NET developer community provides rich resources and support, including: 1. Microsoft's official documents, 2. Community forums such as StackOverflow and Reddit, and 3. Open source projects on GitHub. These resources help developers improve their programming skills from basic learning to advanced applications.

The advantages of C#.NET include: 1) Language features, such as asynchronous programming simplifies development; 2) Performance and reliability, improving efficiency through JIT compilation and garbage collection mechanisms; 3) Cross-platform support, .NETCore expands application scenarios; 4) A wide range of practical applications, with outstanding performance from the Web to desktop and game development.


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

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 Chinese version
Chinese version, very easy to use

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.
