[design pattern series] simple factory

Andy a Hui 2021-09-15 09:55:13
design pattern series simple factory


Factory mode

Factory mode : As the name suggests, it makes this class work like a factory , Production of products , Use it here , We are the production class . The factory model is production , Creating patterns for classes .

It provides a method to create objects in the parent class , Allow subclasses to determine the type of instantiated object .

Binding code to specific classes makes code more vulnerable , More inflexible , extensible , It's difficult to modify .

Programming to an interface , It can isolate a lot of changes that may happen to the system later , extensible .

Used to deal with change , And help us “ Find out what's going to change , Separate them from the same parts ”

Demo

[ Design pattern series ] Simple factory _ Code specification
For example, there is a logistics company , Before, the business was very single , Only do land logistics , as time goes on , Changes in the market , There's also maritime logistics , So how to design an implementation to deal with this uncertainty in business logic , If a kind of air logistics is added in the back , So how will it be designed .

How to only road logistics and maritime logistics , We can just declare it in a separate class , Back through if/eles The way to judge is the logistics , To achieve it . There is no problem in doing so , It can solve the problems facing the business , But it's not the best way to implement it in software development , If you pass if/eles To achieve , So their coupling is too high , Later, if the land logistics is modified , There are too many things that can lead to changes , And it's not easy to scale .

Simple implementation logic

 /// <summary>
/// Marine logistics
/// </summary>
public class AtSeaLogistics
{
/// <summary>
/// Shipping by sea
/// </summary>
public void SendSeaGoods(string goodName)
{
Console.WriteLine(" The sea Send:"+goodName);
}
}

  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
 /// <summary>
/// Land logistics
/// </summary>
public class LandLogistics
{
/// <summary>
/// Land delivery
/// </summary>
public void SendLandGoods(string goodName)
{
Console.WriteLine(" land Send:"+goodName);
}
}

  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
 static void Main(string[] args)
{
int logisticsType = 0; // The default is land transportation
Console.WriteLine(" Start shipping ");
if (logisticsType==0)
{
LandLogistics land = new LandLogistics();
land.SendLandGoods("Iphone 13");
}
else
{
AtSeaLogistics atSea = new AtSeaLogistics();
atSea.SendSeaGoods(" Sea fish ");
}
Console.WriteLine(" Delivery complete ");
Console.ReadKey();
}

  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.

After operation , Due to the default land delivery , Call the land delivery module , Make delivery .
[ Design pattern series ] Simple factory _C#_02
This is actually a very simple , It's also the most common way to write simple logic , There's no problem realizing the function , However, this kind of implementation has great hidden trouble and is not extensible , If a mode of transportation needs to be added later , It may have to be in Main() Method , The coupling between transportation mode and logistics is too high , And it's not easy to expand .

Here's an implementation using the simple factory pattern , Through the interface to achieve their own , They are responsible for their own affairs , Logistics companies don't need to know which way to deliver goods , Just deliver the goods to the delivery factory , The delivery factory decides which method to use according to the goods itself .

Factory mode

 public interface ISendInterface
{
void SendGoods(string goodName);
}

  • 1.
  • 2.
  • 3.
  • 4.
 /// <summary>
/// Land logistics
/// </summary>
public class LandLogistics:ISendInterface
{
/// <summary>
/// Land delivery
/// </summary>
public void SendGoods(string goodName)
{
Console.WriteLine(" land Send:" + goodName);
}
///// <summary>
///// Land delivery
///// </summary>
//public void SendLandGoods(string goodName)
//{
// Console.WriteLine(" land Send:"+goodName);
//}
}

  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
 /// <summary>
/// Marine logistics
/// </summary>
public class AtSeaLogistics:ISendInterface
{
/// <summary>
/// Shipping by sea
/// </summary>
public void SendGoods(string goodName)
{
Console.WriteLine(" The sea Send:" + goodName);
}
//public void SendSeaGoods(string goodName)
//{
// Console.WriteLine(" The sea Send:"+goodName);
//}
}

  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
 /// <summary>
/// Physical distribution management , Mainly used for delivery
/// </summary>
public class LogisticsStoreFactory
{
ISendInterface sendGood = null;
public ISendInterface GetSendInterface(int type)
{
switch (type)
{
case 1:
sendGood = new LandLogistics();
break;
case 2:
sendGood = new AtSeaLogistics();
break;
default:
break;
}
return sendGood;
}
}

  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.

Call implementation logic

 LogisticsStoreFactory logisticsStore = new LogisticsStoreFactory();
// land transportation
ISendInterface loadSend = logisticsStore.GetSendInterface(1);
loadSend.SendGoods("Iphone 13");
// sea transport
ISendInterface atSeaSend = logisticsStore.GetSendInterface(2);
atSeaSend.SendGoods(" Sea fish ");
Console.WriteLine(" Delivery complete ");
Console.ReadKey();

  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.

Now we can see that , Simple factory in the process of implementation , There is no need to focus on how to achieve their own transportation , Only by LogisticsStoreFactory Factory class to get the implementation , Just use it as you like . So decoupling is achieved , Split the call and Implementation , There's no need to pay too much attention to how it's implemented , Just use it .

Applicable scenario

  • During coding , When you can't predict the object category and its specific dependencies , Can use simple factory .
  • Separate the creation and Implementation , Without affecting other products , You can create it yourself , Low coupling , Easy to expand .

Realization way

  • Define each product class , Let each class do its own work , No interference with each other .
  • It's a common interface , Let all products implement this interface .
  • Create an empty factory class , Let it have the ability to acquire products , And return this common interface .
  • Find a reference to the product constructor in the creator code , Change it to a reference to the factory method , At the same time, migrate the code that created the product to the factory method .

Little message

A man's struggle , It's like being pregnant , It's been a long time , It will always be seen .

Life is short , I don't want to pursue what I can't see , I just want to catch what I can see .

I am a A Hui , Thank you for reading , If it helps you , Please like it , forward thank you .

版权声明
本文为[Andy a Hui]所创,转载请带上原文链接,感谢
https://javamana.com/2021/09/20210909145435995Y.html

  1. L'arrivée de marchandises sèches, l'entretien d'emploi Java 12 grandes usines ont réussi à changer d'emploi,
  2. Multiple postures for handling container time in k8s environment
  3. Echarts remove left Gap, Blank
  4. Hotspot Weekly | zoom $100 million, docker fees, $38 billion Data bricks
  5. JsonMappingException: No serializer found for class org.apache.ibatis.executor.loader.javassist.JavassistProxyFactory...
  6. Java. Security. Securerandom source code analysis Java. Security. EGD = file: / dev /. / urandom
  7. When using IntelliJ idea, jump directly and quickly from the mapper interface to mapper.xml
  8. When idea writes SQL in mybatis XML, the solution to the problems of table name, field and red reporting
  9. Spring cloud integrates Nacos
  10. 应届毕业生Java笔试题目,2021大厂Java社招最全面试题,
  11. Liver explosion! Take you to understand Hadoop serialization
  12. linux系列之:告诉他,他根本不懂kill
  13. java版gRPC实战之三:服务端流
  14. RabbitMQ核心知识总结!
  15. linux系列之:告诉他,他根本不懂kill
  16. java版gRPC实战之三:服务端流
  17. RabbitMQ核心知识总结!
  18. 10天拿到字节跳动Java岗位offer,学习Java开发的步骤
  19. 10天拿到字节跳动Java岗位offer,Java知识点思维导图
  20. Résumé des connaissances de base de rabbitmq!
  21. 10天拿到字節跳動Java崗比特offer,Java知識點思維導圖
  22. 10 jours pour obtenir un Byte Jump Java post offer, Java Knowledge point Mind Map
  23. 10 jours pour obtenir l'octet Jump Java post offer, apprendre les étapes du développement Java
  24. Java version of gppc Reality Three: server side stream
  25. Linux Series: Dites - lui qu'il ne connaît pas kill du tout
  26. "Data structure and algorithm" of front end -- binary search
  27. 2020-2021京东Java面试真题解析,如何才能通过一线互联网公司面试
  28. 13 SpringBoot整合RocketMQ实现过滤消息-根据SQL表达式过滤消息
  29. 12 SpringBoot整合RocketMQ实现过滤消息-根据TAG方式过滤消息
  30. 11 SpringBoot整合RocketMQ实现事务消息
  31. 11 springboot Consolidated rocketmq Implementation transaction message
  32. 12 springboot Consolidated rocketmq Implements Filtering messages - Filtering messages according to tag method
  33. 13 springboot Consolidated rocketmq Implementation Filtering messages - Filtering messages according to SQL expressions
  34. linux系列之:告诉他,他根本不懂kill
  35. (1)java Spring Cloud+Spring boot企业快速开发架构之微服务是什么?它的优缺点有哪些?
  36. Oracle 检查 DATE 列 RANGE 分区表已有分区的最大日期时间
  37. ConcurrentHashMap--原理
  38. 2020 - 2021 JD Java interview Real question Analysis, How can interview through First - Line Internet Company
  39. Concurrenthashmap - - Principes
  40. Oracle vérifie l'heure de date maximale d'une partition existante dans la colonne date
  41. Docker Compose 实践及梳理
  42. Qu'est - ce qu'un microservice pour Java Spring Cloud + Spring Boot Enterprise Quick Development architecture?Quels sont ses avantages et ses inconvénients?
  43. Plus sign interview knowledge points in Java
  44. Pratique et organisation de la composition des dockers
  45. Linux Series: Dites - lui qu'il ne connaît pas kill du tout
  46. Convenient CSS and jQuery drop-down menu solution
  47. Linux analog packet loss rate
  48. Redis:我是如何与客户端进行通信的
  49. 15 useful cron work examples commonly used by Senior Linux system administrators
  50. 24个 JavaScript 循环遍历方法,你都知道吗?
  51. Reading notes of JavaScript advanced programming (3rd Edition) 4
  52. 30分钟学会Docker里面开启k8s(Kubernetes)登录仪表盘(图文讲解)
  53. 24 méthodes de traversée de boucle Javascript, vous savez?
  54. 30 minutes pour apprendre à ouvrir le tableau de bord k8s (kubernets) dans le docker (explication graphique)
  55. Redis: comment je communique avec les clients
  56. Wsl2: Windows native Linux subsystem
  57. 30分钟学会Docker里面开启k8s(Kubernetes)登录仪表盘(图文讲解)
  58. Python高级用法总结(8)-函数式编程
  59. 261页前端面试题宝典,JavaScript变量声明提升
  60. The performance of JVM and Java applications of the same version differs by 30% on X86 and aarch64 platforms. Why?