2、工厂模式
一、简单工厂模式
在一个工厂类中暴露一个带参数的方法,根据方法参数实例化所需要的对象,由于工厂中包含了判断逻辑,不符合(OCP),只适应于简单固定的几个对象,后期新增对象,需要修改工厂方法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 | public static class SimpleFactory { public static IAnimal CreateAnimalInstance(EAnimalType eAnimalType) { return eAnimalType switch { EAnimalType.Bird => new Bird(), EAnimalType.Dog => new Dog(), _ => throw new NotImplementedException(), }; } } public enum EAnimalType { Bird, Dog } public interface IAnimal { string Name { get ; } void Eah(); } public class Bird : IAnimal { public String Name => throw new NotImplementedException(); public void Eah() { throw new NotImplementedException(); } } public class Dog : IAnimal { public String Name => throw new NotImplementedException(); public void Eah() { throw new NotImplementedException(); } } |
二、反射模式,这是基本简单模式的优化,根据需要创建的实例全名通过反射创建实例,这样去掉了简单模式中的逻辑判断,从而遵循了OCP原则
public static class ReflectFactory { public static IAnimal? CreateAnimalInstance(string typeName) { var typeInfo = Type.GetType(typeName,true,true); return typeInfo?.Assembly.CreateInstance(typeName, true) as IAnimal; } }
三、方法模式,每一个产品设计一个工厂接口,同类的产品实例实现自己的工厂,客户端使用时,实例化不同的工厂,实际也是简单工厂的优化,把判断逻辑提供给客户端,由具体工厂解耦实例对象
interface IMethodFactory { IAnimal CreateAnimalInstance(); } public class BirdFactory : IMethodFactory { public IAnimal CreateAnimalInstance() { return new Bird(); } } public class DogFactory : IMethodFactory { public IAnimal CreateAnimalInstance() { return new Dog(); } }
四、抽象模式,抽象模式或以说是多个方法模式工厂的聚合
interface IAbstractFactory { IAnimal CreateAnimalInstance(); IPlant CreatePlantInstance(); } public class AbstractFactoryA : IAbstractFactory { public IAnimal CreateAnimalInstance() { return new Bird(); } IPlant IAbstractFactory.CreatePlantInstance() { return new PlantA(); } } public class AbstractFactoryB : IAbstractFactory { public IAnimal CreateAnimalInstance() { return new Dog(); } IPlant IAbstractFactory.CreatePlantInstance() { return new PlantB(); } }
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步