关于抽象工厂的一些理解

抽象工厂最大限度的让代码重复使用,其实也是设计模式中的模板模式,好了至此我们学习了两种了,一种是接口,一种是抽象工厂,二者结合起来更好,关于前面的代理,数据集扩展还有lanm表达式的一些应用,代理,事件,等应用场合,打码简洁性等,我花一段时间来让自己的知识更加系统化,也算对以前知识的一些总结,和自己认为一些比较重要的例子

看代码

 public class RowGenericFactroy<T>
    {
        public T Create(string typename)
        {
            if(string.IsNullOrEmpty(typename))
                throw new ArgumentNullException("yupename");
            return (T)Activator.CreateInstance(Type.GetType(typename));
        }
    }
 /// <summary>
    ///这是 RowGenericFactroyTest 的测试类,旨在
    ///包含所有 RowGenericFactroyTest 单元测试
    ///</summary>
    [TestClass()]
    public class RowGenericFactroyTest
    {
        interface Iproduct
        {

        }
        class Conproduct : Iproduct
        {

        }
        interface IUser
        {
        }
        class ConUerA : IUser 
        {
        
        }
        [TestMethod]
        public void Test()
        {
            var typename = typeof(Conproduct).AssemblyQualifiedName;
            Trace.WriteLine(typename);
            var product = new RowGenericFactroy<Iproduct>().Create(typename);
            Assert.IsNotNull(product);
            Assert.IsInstanceOfType(product, typeof(Conproduct));
            Assert.IsTrue(product is Iproduct);

            var user = new RowGenericFactroy<IUser>().Create(typeof(ConUerA).AssemblyQualifiedName);

            Assert.IsNotNull(user);
            Assert.IsInstanceOfType(user, typeof(ConUerA));
            Assert.IsTrue(user is IUser);

        }

    }

以上是调用,怎么样,这个也符合里氏替换原则,依赖抽象而非具体,这样就省略UserFactroy和ProductFactroy达到公用的目的,实际应用中一般根据配置文件获取相应类型名称

原文地址:https://www.cnblogs.com/wangchuang/p/2982310.html