#设计模式#之抽象工厂模式
基础概念:抽象工厂类、具体工厂类、抽象产品类、具体产品类
适用领域:不断增加产品种类
第一步:创建抽象产品类以及一个具体产品类
//抽象产品类,只有一个功能获取token public abstract class abstractPlatform { public abstract string GetAccessToken(string code); } public class Tencent : abstractPlatform { public override string GetAccessToken(string code) { return this + " qq token"; } }
第二步:创建一个抽象工厂类与具体工厂类
// 抽象工厂类 public abstract class Platform { public abstract abstractPlatform createPlatform(); } //具体工厂类 public class TencentFactory : Platform { public override abstractPlatform createPlatform() { return new Tencent(); } }
第三步:创建用户调用类
//客户端调用 public class ClientPlatform { abstractPlatform _instance; public ClientPlatform(Platform platform) { _instance = platform.createPlatform(); } //具体业务逻辑 public string GetAccessToken(string code) { return _instance.GetAccessToken(code); } }
示例代码
public static void Main(string[] args) { Platform platform = new TencentFactory(); //腾讯 ClientPlatform client = new ClientPlatform(platform); string code = client.GetAccessToken("code"); Console.WriteLine(code); Console.ReadLine(); }
//增加一个产品
1、增加一个具体工厂类、具体产品类即可
public class Sina : abstractPlatform { public override string GetAccessToken(string code) { return this + " sina token"; } } public class SinaFactory : Platform { public override abstractPlatform createPlatform() { return new Sina(); } }
示例代码
public static void Main(string[] args) { //1. Platform platform = new TencentFactory(); //腾讯 ClientPlatform client = new ClientPlatform(platform); string code = client.GetAccessToken("code"); Console.WriteLine(code); //2.新增的产品类 platform = new SinaFactory(); //新浪 client = new ClientPlatform(platform); code = client.GetAccessToken("code"); Console.WriteLine(code); Console.ReadLine(); }