Click here to view the full design patterns series article navigation

introduction

The last article introduced the simple factory pattern in design patterns -C# Design patterns (2)- Simple factory model , This article will introduce Factory method model , Transformation in simple factory mode ;

Introduction to the factory method model

Factory method (FactoryMethod) Pattern : Defines an interface for creating objects , Let the subclass decide which class to instantiate . Factory methods delay the instantiation of a class into its subclasses ;

The disadvantages of the simple factory model were discussed in the last article , Factory classes centralize all of the product creation logic , If it doesn't work properly, it will have a great impact on the system . If we add a product , We need to add case Branch condition , Modify the original class , So we're not only open to expansion , It's also open to change , Contrary to “ to open up - closed ” principle , therefore We optimize the simple factory model , Pull out an interface to the factory , Here's the factory method model

chart

( From Dahua design pattern )

Application example

The example here still uses the example in the previous article : There are many kinds of databases on the market ,Oracle、SqlSever、Mysql etc. ; For example, we now need to write a general data processing , If new 、 Update and other operations , It can switch any database , Can call the corresponding version of the database add or update operation ;

The following class diagram 、 The code will take database operation as an example ;

Class diagram

Code instance

notes : Here is just an example , No business logic ;

Create data operation abstract class

To add 、 Update as an example ;

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks; namespace FactoryMethod
{
/// <summary>
/// Database operation abstract class
/// </summary>
public abstract class AbstractDataBaseOpr
{
/// <summary>
/// newly added
/// </summary>
public abstract bool Insert(); /// <summary>
/// to update
/// </summary>
/// <returns></returns>
public abstract bool Update();
}
}

Oracle Data operation class

Inherit the above database operation abstract class

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks; namespace FactoryMethod
{
/// <summary>
/// oracle operation
/// </summary>
public class OracleDbOpr : AbstractDataBaseOpr
{
/// <summary>
/// newly added
/// </summary>
public override bool Insert()
{
Console.WriteLine("Oracle The new record ");
return true;
} /// <summary>
/// to update
/// </summary>
/// <returns></returns>
public override bool Update()
{
Console.WriteLine("Oracle Update record ");
return true;
} }
}

SqlServer Data operation class

Inherit the above database operation abstract class

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks; namespace FactoryMethod
{
/// <summary>
/// sqlServer operation
/// </summary>
public class SqlServerDbOpr : AbstractDataBaseOpr
{
/// <summary>
/// newly added
/// </summary>
public override bool Insert()
{
Console.WriteLine("SqlServer The new record ");
return true;
} /// <summary>
/// to update
/// </summary>
/// <returns></returns>
public override bool Update()
{
Console.WriteLine("SqlServer Update record ");
return true;
} }
}

establish DB Factory interface

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks; namespace FactoryMethod
{
/// <summary>
/// DB Factory interface
/// </summary>
public interface IDbFactory
{
/// <summary>
/// establish db Examples of operation
/// </summary>
/// <returns></returns>
AbstractDataBaseOpr CreateDbOpr();
}
}

Oracle Factory

Implementation interface

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks; namespace FactoryMethod
{
/// <summary>
/// oracle db factory
/// </summary>
public class OracleDbFactory : IDbFactory
{
/// <summary>
/// Create a database operation instance
/// </summary>
/// <returns></returns>
public AbstractDataBaseOpr CreateDbOpr()
{
return new OracleDbOpr();
}
}
}

SqlServer Factory

Implementation interface

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks; namespace FactoryMethod
{
/// <summary>
/// SqlServer db factory
/// </summary>
public class SqlServerDbFactory : IDbFactory
{
/// <summary>
/// Create a database operation instance
/// </summary>
/// <returns></returns>
public AbstractDataBaseOpr CreateDbOpr()
{
return new SqlServerDbOpr();
}
}
}

Business call

oracle Database and sqlserver Database operations are called separately

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks; namespace FactoryMethod
{
class Program
{
static void Main(string[] args)
{
//oracle operation
IDbFactory dbFactory1 = new OracleDbFactory();
AbstractDataBaseOpr opr1 = dbFactory1.CreateDbOpr();
opr1.Insert();
opr1.Update(); Console.WriteLine("-----------------------------------------"); // Switch to a sqlserer
IDbFactory dbFactory2 = new SqlServerDbFactory();
AbstractDataBaseOpr opr2 = dbFactory2.CreateDbOpr();
opr2.Insert();
opr2.Update(); Console.ReadKey();
}
}
}

The results

Advantages and disadvantages

advantage

  • Users only need to care about the factory corresponding to the required product , There's no need to focus on how to create .
  • When adding new products , New product categories and corresponding factory categories need to be added , It won't affect other products , Comply with opening and closing principle .

shortcoming

When new products need to be added , New product categories need to be added , The corresponding factory class needs to be added

C# Design patterns (3)- More articles on the factory method pattern

  1. C# Design patterns (3)—— Factory method model

    One . Concept : Defines an interface for creating objects , Let the subclass decide which class to instantiate , The factory method delays the instantiation of a class to its subclasses . Two . Code implementation namespace Factory method pattern of design pattern { /// <summary&g ...

  2. Enjoy design patterns (C#) - Factory method model (Factory Method Pattern)

    original text : Enjoy design patterns (C#) - Factory method model (Factory Method Pattern) [ Index page ][ Source download ] Enjoy design patterns (C#) - Factory method model (Factory Method Pa ...

  3. C# Design patterns (3)—— Factory method model ( turn )

    C# Design patterns (3)—— Factory method model   One . introduction In the simple factory mode, we talk about the disadvantages of the simple factory mode , One thing is —— Simple factory mode system is difficult to expand , Once you add a new product, you have to modify the simple factory method , This will result in a simple factory implementation logic over ...

  4. Java Factory method pattern of design pattern ( turn ) Implementations are abstract factories ?

    Java Factory method pattern of design pattern editor : The author of Qin Li :Java Research Organization    2009-02-25    source :IT168 Website   Text Tag:  Design patterns  Java [IT168 Technical articles ]         ...

  5. php Factory method pattern of design pattern

    php Factory method pattern of design pattern Factory method model Factory method model (Factory Method Pattern) Also known as the factory mode , It's also called virtual constructor (Virtual Constructor) Patterns or polymorphic factories (Pol ...

  6. java 23 - 1 Factory method pattern of design pattern

    Reprint : JAVA Factory mode of design mode ( Simple factory model + Factory method model )

  7. Java Design patterns And Factory method model

    1. The benefits of using design patterns : Can improve the repeatability of the code , Make code easier to understand , Ensure the reliability of the code . 2. Factory mode definition : Is to create a factory class to create the class you need , Factory pattern includes factory pattern and abstract factory pattern , The abstract factory pattern is the factory ...

  8. Android Design pattern series -- Factory method model

    Factory method model , It's often a pattern for beginners of design patterns , You bet , Some people call it the most typical and inspiring model .android Too many factory classes are used in , One of them is the factory method model , Of course, there are many factories that don't use the factory method mode , Just tools ...

  9. Design pattern - Factory method model (Factory Method design pattern)

    1. Mode intent :  Defines an interface for creating objects , Let the subclass decide which class to instantiate , The factory method delays the instantiation of a class to its subclasses . 2. Alias (Virtual Constructor) 3. structure 4. Factory method model C ...

  10. Set sail again , One of my study notes JavaScript Design patterns 06( Factory method model )

    Last time I introduced you to the simple factory model , I believe you have a preliminary understanding of the creative design pattern , What I will introduce to you this time is the factory method model . Factory method model Factory method model (Factory Method): Create product classes by abstracting them ...

Random recommendation

  1. Mysql Master slave copy , Read / write separation (mysql-proxy), Double main structure complete construction process

    Let's introduce MySQL Master slave copy , Read / write separation , Double main structure complete construction process , Not too much theory , Only the process of experiment and configuration . Mysql Master slave copy ( Reprint please indicate the source , Blog address :)  The principle is master Log changes to binary log (bina ...

  2. JavaScript Learning notes - Regular expressions (RegExp object )

    Regular expressions (RegExp object )   1. Literal amount of regular expression , Compile after the script loads . If your regular expression is constant , You can get better performance in this way , It's not recompiled when it's reused : 2. Created using the constructor RegExp, Provides ...

  3. 8.python Number in

    python The creation of digital objects in is as follows , a = 123 b = 1.23 c = 1+1j You can enter numbers directly , And then assign it to the variable . It's also a way to use classes : a = int(123) b = float(1. ...

  4. The establishment of receiving list and its DFS, BFS;;;

    // The realization of the establishment of graph -> There are two representation methods of adjacent junction matrix and adjacent junction table #include <cstdio> #include <cstdlib> //#define _OJ_ int vis ...

  5. [Javascript] Using JSHint for Linting with Gulp

    gulpfile.js var gulp = require('gulp'); var jshint = require('gulp-jshint'); var stylish = require(' ...

  6. jquery Variables and primitives js The relationship of variables

    Actually js Variables and jquery Nothing is different , It can also be direct var  hhhh=$("header"); But when it comes to hhh Still need to use jquery The way , And not js The original way .

  7. Java Basics - Operating principle and variables (01)

    java Operation principle Write by hand java The file is compiled by the compiler .class file , And then the interpreter translates class Files run in machine language . Java Classification of annotations in Single line comment format : // Annotation text multiline annotation format : /* Note text */ ...

  8. beautifulsoup Library usage

    Introduction and installation Beautiful Soup It's a HTML/XML The parser , The main function is also how to parse and extract HTML/XML data .BeautifulSoup Used to resolve HTML Relatively simple , API Very human ...

  9. windows in ,VS2017 Next , stay Cmake Add OpenCV rely on

    OpenCV_DIR  -----D:/OpenCV/3.3.0/opencv/build/x64/vc14/lib Only this directory cmake Just recognize .. It seems to be because we found the corresponding OpenCvConfig.c ...

  10. [Oracle]Oracle Fail Safe And SQLNET.AUTHENTICATION_SERVICES Relationship

    The phenomenon : In the use of OFS (Oracle Fail Safe) In the environment of , Put the database SQLNET.AUTHENTICATION_SERVICES from NTS Change it to NONE after , When from Oracle Fa ...