淺談C#設計模式之工廠模式
更新時間:2014年12月17日 11:01:54 投稿:hebedich
這篇文章主要介紹了淺談C#設計模式之工廠模式,需要的朋友可以參考下
工廠模式和簡單工廠有什么區(qū)別。廢話不多說,對比第一篇例子應該很清楚能看出來。
優(yōu)點: 工廠模式彌補了簡單工廠模式中違背開放-封閉原則,又保持了封裝對象創(chuàng)建過程的優(yōu)點。
復制代碼 代碼如下:
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();
這里主要是對比了下和簡單工廠模式的區(qū)別,記錄下來,以防自己搞混。