当我们通过工厂方法完成对象创建的时候,我们的前端调用和后台实现完全解耦。
给一个新的dll,就可以实现无编译的更新
简单工厂就是个我们后续更多设计模式的学习,做的一个铺垫,和基础。
简单工厂实习的基本步骤:
1.根据实际需求,封装变化(把要完成的任务,抽象为接口)
2.根据接口,编写不同的实现类。
一般的代码:经过分析,扩展性几乎没有。
按照OOP的基本原则–>开-闭原则(开放增加,封闭修改)
OOP告诉我们:写程序尽量体现"高内聚,低耦合"
低耦合:也就是对象或者一个模块,和另一个对象,或者另一个模块,他们之间不是直接依赖关系,比如对象使用,不是直接使用,而是通过工厂完成。也就是意味着对象的产生做了延迟。
常规设计(不用使用简单工厂类) 接口
public interface ICamSDK
{
bool Start();
bool Close();
}
子类
public class BaslerCamSDK : ICamSDK
{
public bool Close()
{
// 实际开发中,放入具体的实现内容,其实这些都是要封装到类库中的,才是最后的商用
Console.WriteLine("Basler close");
return true;
}
public bool Start()
{
Console.WriteLine("Basler close");
return true;
}
}
子类
public class HikCamSDK : ICamSDK
{
public bool Close()
{
Console.WriteLine("HikCam close");
return true;
}
public bool Start()
{
Console.WriteLine("HikCam start");
return true;
}
}
HikCamSDK需要和之前类的设计名字相同,因为就是调用它 简单工厂类
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Configuration;
using 设计模式之简单工厂模式.CameraSDK;
namespace 设计模式之简单工厂模式
{
class SimpleFactory
{
// 1. 根据用户的需求创建对象(这个需求,我们可以动态的配置到配置文件中)
private static string camType = ConfigurationManager.AppSettings["camType"].ToString();
// 2. 编写工厂方法
public static ICamSDK CamSDKCreator()
{
if (camType == "HikCamSDK")
{
return new HikCamSDK();
}
else if (camType == "BaslerCamSDK")
{
return new BaslerCamSDK();
}
else
{
// 默认
return null;
}
}
}
}
主程序调用
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using 设计模式之简单工厂模式.CameraSDK;
namespace 设计模式之简单工厂模式
{
class Program
{
static void Main(string[] args)
{
// 1. 通常做法,不使用简单工厂设计模式
// 经过分析,这样使用太繁琐,扩展性几乎没有,所以诞生了简单工厂模式
ICamSDK camSDK = new HikCamSDK();
camSDK.Start();
camSDK.Close();
Console.ReadLine();
// 2. 使用简单工厂设计模式
ICamSDK camSDK2 = SimpleFactory.CamSDKCreator();
camSDK2.Start();
camSDK2.Close();
Console.ReadLine();
}
}
}
修改配置,即可改变程序



