2 简单工厂模式

  public class CreateFactory
    {
        public static ICreate GeneratorCreate(string createName)
        {
            switch (createName)
            {
                case "People":
                    return new People();
                case "Animal":
                    return new Animal();
                default:
                    throw new NotImplementedException();
            }
        }
    }
    /// <summary>
    /// 人类实现工厂接口
    /// </summary>
    public class People : ICreate
    {

        #region ICreate 成员

        public string Create()
        {
            return "创建人类";
        }

        #endregion
    }
    /// <summary>
    /// 动物实现工厂接口
    /// </summary>
    public class Animal : ICreate
    {

        #region ICreate 成员

        public string Create()
        {
            return "创建动物";
        }

        #endregion
    }
    /// <summary>
    /// 简单工厂接口,返回值类型
    /// </summary>
    public interface ICreate
    {
        string Create();
    }
View Code

简单工厂:根据提供给它的数据,返回一个类的实例,通常它返回的类都有一个公共的父类(或者接口对象)
简单工厂的核心是实例化对象,简单工厂实例化的类具有相同的接口或者基类,在子类比较固定,并不需要扩展时候,可以使用简单工厂,
简单工厂的优点是:可以根据参数获取相应的实例,避免了直接实例化,减低了耦合性,
缺点是可实例化的类型再编译期间已经确定,如果增加新类型,需要修改工厂,不符合OCP(开闭原则),简单工厂需要知道所有要生成的类型,当子类过多,或者子类层级过多则不适合使用简单工厂

调用:

CreateFactory.GeneratorCreate("People").Create()

 

posted @ 2016-07-04 16:28  那就让我这样吧  阅读(160)  评论(0编辑  收藏  举报