浅谈C#设计模式之工厂模式
作者:hebedich 时间:2021-12-17 16:06:48
工厂模式和简单工厂有什么区别。废话不多说,对比第一篇例子应该很清楚能看出来。
优点: 工厂模式弥补了简单工厂模式中违背开放-封闭原则,又保持了封装对象创建过程的优点。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DesignModel
{
public interface Factory
{
JS createjs();
}
public class JS
{
public int NumA { get; set; }
public int NumB { get; set; }
public virtual int GetResult()
{
return 0;
}
}
public class Add1 : JS
{
public override int GetResult()
{
return NumA + NumB;
}
}
public class Sub1 : JS
{
public override int GetResult()
{
return NumA - NumB;
}
}
public class AddFactory : Factory
{
public JS createjs()
{
return new Add1();
}
}
public class SubFactory: Factory
{
public JS createjs()
{
return new Sub1();
}
}
}
客户端调用:
Factory factory = new AddFactory();
JS js = factory.createjs();
js.NumA = 1;
js.NumB = 2;
Console.WriteLine( js.GetResult());
Factory f = new SubFactory();
JS J= f.createjs();
J.NumA = 9;
J.NumB = 0;
Console.WriteLine(J.GetResult());
Console.ReadLine();
这里主要是对比了下和简单工厂模式的区别,记录下来,以防自己搞混。
标签:C#,设计模式,工厂模式
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
泛谈Java中的不可变数据结构
2022-02-18 00:12:54
java实现连连看游戏课程设计
2023-10-30 13:18:37
C#实现根据图片的链接地址获取图片的后缀名
2022-08-04 04:30:58
JAVA使用Gson解析json数据实例解析
2021-08-23 14:50:56
详解使用Spring的BeanPostProcessor优雅的实现工厂模式
2023-01-14 02:15:53
VisualStudio2019安装C#环境的实现方法
2021-11-02 18:36:31
![](https://img.aspxhome.com/file/2023/6/84436_0s.png)
jdbc与druid连接池的使用详解
2023-09-18 17:50:11
Java多线程:生产者与消费者案例
2021-06-30 05:47:08
![](https://img.aspxhome.com/file/2023/0/89940_0s.png)
Java如何解析html中的内容并存到数据库详解
2023-11-29 05:08:32
java数据结构与算法之快速排序详解
2023-02-23 10:23:43
SpringBoot创建WebService方法详解
2022-02-08 10:29:31
![](https://img.aspxhome.com/file/2023/1/79821_0s.png)
Spring Bean生命周期之属性赋值阶段详解
2022-09-28 04:34:11
C#中累加器函数Aggregate用法实例
2023-03-21 10:28:30
Android 判断是否有外网连接
2022-12-02 21:48:13
C# Volatile的具体使用
2023-11-21 11:14:50
![](https://img.aspxhome.com/file/2023/0/71740_0s.png)
深入探究Java线程的创建与构造方法
2023-05-29 22:02:45
![](https://img.aspxhome.com/file/2023/5/72315_0s.png)
Android自定义流式布局的实现示例
2022-10-14 23:30:44
![](https://img.aspxhome.com/file/2023/0/104630_0s.png)
C#二进制读写BinaryReader、BinaryWriter、BinaryFormatter
2022-03-07 23:01:28
SpringMVC数据输出相关知识总结
2022-04-06 10:35:06
![](https://img.aspxhome.com/file/2023/1/62711_0s.png)
Spring Boot 在启动时进行配置文件加解密的方法详解
2023-11-12 17:13:54