2、工厂模式
一、简单工厂模式
在一个工厂类中暴露一个带参数的方法,根据方法参数实例化所需要的对象,由于工厂中包含了判断逻辑,不符合(OCP),只适应于简单固定的几个对象,后期新增对象,需要修改工厂方法
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(); } }