public interface IYunSuan
{
double getResult(int num1, int num2);
}
public class jia : IYunSuan
{
public double getResult(int num1, int num2)
{
return num1 + num2;
}
}
public class jian : IYunSuan
{
public double getResult(int num1, int num2)
{
return num1-num2;
}
}
public class cheng : IYunSuan
{
public double getResult(int num1, int num2)
{
return num1*num2;
}
}
public class chu : IYunSuan
{
public double getResult(int num1, int num2)
{
if (num2 == 0) return 0;
return num1/num2;
}
}
//////////////
//簡單工廠,專門生產(chǎn)對象
public static IYunSuan createYunSuanObj(string type)
{
switch (type)
{
case "+":return new jia();
case "-": return new jian();
case "*": return new cheng();
case "/": return new chu();
}
return null;
}
//工廠方法模式,把簡單工廠分解
public interface IFactory
{
IYunSuan createYunSuanObj();
}
public class jiaFactory : IFactory
{
public IYunSuan createYunSuanObj()
{
return new jia();
}
}
public class jianFactory : IFactory
{
public IYunSuan createYunSuanObj()
{
return new jian();
}
}
public class chengFactory : IFactory
{
public IYunSuan createYunSuanObj()
{
return new cheng();
}
}
public class chuFactory : IFactory
{
public IYunSuan createYunSuanObj()
{
return new chu();
}
}
前端:
static void Main(string[] args)
{
//簡單工廠模式
//var jia=simpleFactory.createYunSuanObj("+");
//var result=jia.getResult(1,2);
//Console.WriteLine(result);
//Console.ReadLine();
//工廠方法模式
IFactory factory = new jiaFactory();
var jia=factory.createYunSuanObj();
var result=jia.getResult(1, 2);
Console.WriteLine(result);
Console.ReadLine();
}
總結(jié):定義一個創(chuàng)建對象的接口,讓子類決定實(shí)例化哪個類,工廠模式使得一個類的實(shí)例化延遲到其子類。是基于簡單工廠的擴(kuò)展模式,解耦了簡單工廠的工廠類,符合了幾大原則
優(yōu)點(diǎn):解耦
缺點(diǎn):代碼量增加N多,讓人蛋疼。
創(chuàng)新互聯(lián)總部坐落于成都市區(qū),致力網(wǎng)站建設(shè)服務(wù)有成都網(wǎng)站設(shè)計(jì)、網(wǎng)站建設(shè)、網(wǎng)絡(luò)營銷策劃、網(wǎng)頁設(shè)計(jì)、網(wǎng)站維護(hù)、公眾號搭建、小程序制作、軟件開發(fā)等為企業(yè)提供一整套的信息化建設(shè)解決方案。創(chuàng)造真正意義上的網(wǎng)站建設(shè),為互聯(lián)網(wǎng)品牌在互動行銷領(lǐng)域創(chuàng)造價值而不懈努力!