What is factory mode
Factory pattern is one of the most commonly used design patterns , It belongs to creation mode .
somewhat :
- decoupling , You can separate the creation of objects from the process
- Reduce the amount of code , Easy to maintain
When to use ?
When an abstract class has multiple implementations , When multiple instantiations are required , Consider using the factory model .
such as : Login abstract class ILoginBusiness
, It has 2 Implementation , A login with user name and password , A login with a mobile phone number verification code
public interface ILoginBusiness
{
Task Login(LoginInputDTO input);
}
public class MobileCodeLogin : ILoginBusiness
{
public Task Login(LoginInputDTO input)
{
// todo
}
}
public class UserNameAndPasswordLogin : ILoginBusiness
{
public Task Login(LoginInputDTO input)
{
// todo
}
}
In the same way , We will instantiate according to certain conditions , such as loginType
ILoginBusiness loginBusiness;
if (loginType == 1)
{
loginBusiness = new MobileCodeLogin();
}
else
{
loginBusiness = new UserNameAndPasswordLogin()
}
When there are multiple instances , More is needed ifelse perhaps switch, The function of the factory pattern is to put this method of building objects in the factory class to solve , Unified management and maintenance .
Realization way
public interface ILoginFactory
{
ILoginBusiness Create(LoginInputDTO inputDto);
}
public class LoginFactory : BaseBusiness, ILoginFactory, ITransientDependency
{
public ILoginBusiness Create(LoginInputDTO inputDto)
{
return inputDto.LoginType == LoginType.UserNameAndPwd
? AppDependencyResolver.Current.GetService<UserNameAndPwdLogin>()
: (ILoginBusiness)AppDependencyResolver.Current.GetService<MobileCodeLogin>();
}
public LoginFactory(IRepository repository) : base(repository)
{
}
}
If you use new To instantiate , You need to add the parameters in the constructor to the factory constructor , So here's one AppDependencyResolver
, there AppDependencyResolver.Current.GetService<T>
It's from the present IOC Get the injected instance in the container , So before MobileCodeLogin
and UserNameAndPasswordLogin
It needs to be injected into IOC In the example , In our project, it is inheritance ITransientDependency
public class AppDependencyResolver
{
private static AppDependencyResolver _resolver;
public static AppDependencyResolver Current
{
get
{
if (_resolver == null)
throw new Exception("AppDependencyResolver not initialized");
return _resolver;
}
}
// stay startUp Of ConfigureService Last , Join in AppDependencyResolver.Init(services.BuildServiceProvider());
public static void Init(IServiceProvider service)
{
_resolver = new AppDependencyResolver(service);
}
private AppDependencyResolver(IServiceProvider serviceProvider)
{
_serviceProvider = serviceProvider;
}
private readonly IServiceProvider _serviceProvider;
public object GetService(Type serviceType)
{
return _serviceProvider.GetService(serviceType);
}
public T GetService<T>()
{
return _serviceProvider.GetService<T>();
}
}
About the unit measurement of the factory
About the factory , We just need to test whether the returned object is what we need , As for the execution of the object, you don't need to care
[Theory(DisplayName = " Test login factory ")]
[InlineData(LoginType.MobileCode, typeof(MobileCodeLogin))]
[InlineData(LoginType.UserNameAndPwd, typeof(UserNameAndPwdLogin))]
public void CreateTests(LoginType loginType, Type expectedType)
{
Mock<IRepository> mock = new Mock<IRepository>();
ILoginFactory factory = new LoginFactory(mock.Object);
var login = factory.Create(new LoginInputDTO()
{
LoginType = loginType
});
Assert.IsType(expectedType, login);
}
.Net Core More articles about using factory patterns in
- (13)ASP.NET Core Options mode in (Options)
1. Preface Options (Options) Patterns are about configuration (Configuration) An extension of the function of . stay 12 Chapter (ASP.NET Core Configuration 2 in )Configuration This function has been introduced in ( Bind to entity class . Bind to pair ...
- PHP in “ Simple factory model ” Instance to explain
Original article , Reprint please indicate the source :http://www.cnblogs.com/hongfei/archive/2012/07/07/2580776.html Simple factory model :① Abstract base class : Class to define abstract methods , ...
- JS Factory mode in
. A chestnut : var BicycleShop = function(){}; BicycleShop.prototype = { sellBicycle : function( model ){ va ...
- Spring Factory mode and singleton mode in
Spring Preliminary knowledge ( Suitable for small and medium-sized projects ) effect : Integrate and manage other frameworks Factory mode : A a = new A( ); Write the object to be created by the class to the factory , Unified management package com.spring; pu ...
- 【QtAV】QtAV Factory mode in
QtAV The factory pattern is widely used in various modules of the , The implementation is introduced below . Use of factory mode With VideoRenderer Class as an example , He contains the following 3 A factory pattern related approach ,Register Method is used to give a product <c ...
- spring Factory mode in
spring Of bean The creation principle of is that the framework uses reflection to create instance objects Factory mode : Factories help us create objects : There is a class that helps us create objects , We call this class factory class . for example :Plane plane = PlaneFac ...
- PHP in “ Simple factory model ” Instance to explain ( turn )
? 1 2 3 4 5 6 7 8 Original article , Reprint please indicate the source :http://www.cnblogs.com/hongfei/archive/2012/07/07/2580776.html Simple ...
- c# Medium simple factory mode
Operation class public class yunsuan { public static operation create(string operate) { operation oper = null; s ...
- 【 original 】EntityFramework Core Use in CodeFirst Mode time PowerShell Version problems and solutions
One . describe : In the use of Entity Framework Core when , Use CodeFirst Pattern , stay VS Medium PMC(nuget Package management Console ) The console interface uses the following commands : Install-P ...
- ASP.NET Core Middleware activation based on factory in
IMiddlewareFactory/IMiddleware It is the extension point of middleware activation . UseMiddleware The extension method checks whether the registered type of middleware is implemented IMiddleware. If it is , Is used in the container ...
Random recommendation
- 20145213《 Information security system design basis 》 Experiment 1 Linux Configuration of development environment
Beijing Institute of Electronic Science and technology (BESTI) real Examination newspaper Sue Course : Information security system design basis class :1452 full name : Huang Yaqi Qi Wei Student number :20145213 20145222 achievement : The instructor : Lou Jiapeng Date of experiment :2016 ...
- The original can be seen at a glance 、Maven establish web project
establish maven- project If pom.xml File error Right-click on the project -->Maven-->update Project The detailed steps Above picture Next 2. continue Next 3. choose maven-a ...
- BZOJ-3524 Couriers Persistent line tree
Persistent line tree , In fact, it is a kind of chairman tree .. 3524: [Poi2014]Couriers Time Limit: 20 Sec Memory Limit: 128 MB Submit: 1124 Sol ...
- Front end frame and UI collocation
If it is Angular Then choose Ionic ( A good pair CP) If it is Vue Then choose Vux ( be based on WeUI) If it is jQuery Then choose Framework7 (iOS and Android Double skin ) ...
- bower Common commands
bower install loadash --save bower uninstall loadash --save bower init bower install loadash#2.2.1 b ...
- Periodical :DOI :10.3969/j.issn.1001-2400.2012.01.008
DOI:10.3969/j.issn.1001-2400.2012.01.008 “/” Divided into prefix and suffix two parts, separated by a slash in the middle , The prefix is divided into two parts by dots . "DOI": A journal article ...
- Ghostscript.Net Pdf turn Image
demand : The project needs to realize PPT turn Image The function of , In the previous project, we used Office COM Functions implemented by components , adopt .NET And Office COM Component interoperability (Interop) To operate Office file But in life ...
- ecshop Query the logistics information according to the order number
The goal is : On the order details page, you can query the current logistics information according to the order . design sketch : Ideas : Click to asynchronously request Express query api, Accept the return information , Splicing . Code : admin Next :order_info.htm // One : Insert at the top jquery, stay ...
- beta edition “ Good enough. ”/ Test matrix
It can interact in real time through the corresponding location information of the map fish , It is convenient for users to operate . Test matrix
- Cockroachdb Two 、 Manual deployment
Two Cluster manual deployment ** demand ** a Locally installed CockroachDB b can SSH Access each machine , Used to distribute binaries and certificates c port 26257 Used for cluster internal communication and client access connection HAProxy 8080 ...