设计模式-工厂方法模式(factoryMethod pattern)

来源:互联网 发布:bp神经网络数据归一化 编辑:程序博客网 时间:2024/06/07 01:42

名称:工厂模式

说说:别管这钱怎么来的,给你就用就行了

动机:

适用性:

参与者:

结果:定义了一个创建对象的接口,由子类决定要实例化哪个类,将创建过程推迟到子类

类图:


说明:实现了产品的生产者和调用者解耦,即不管对象的实例化有多么的复杂,有多少的依赖,对象的调用者都无需关心。

demo c#:

namespace factoryMethod{    class Program    {        static void Main(string[] args)        {            iFactory factory = new factory();            iProduct pa = factory.createProduct("A");            pa.showProductDesc();            iProduct pb = factory.createProduct("B");            pb.showProductDesc();            Console.Read();        }    }    // main code    interface iProduct {       void showProductDesc();    }    class productA : iProduct {        public void showProductDesc() {             Console.WriteLine("this is productA");        }    }    class productB : iProduct {        public void showProductDesc() {            Console.WriteLine("this is productB");        }    }    interface iFactory {        iProduct createProduct(string type);    }    class factory : iFactory {        public iProduct createProduct(string type) {            switch (type){                case "A":                    return new productA();                case "B":                    return new productB();                default:                    return null;            }                        }    }}


0 0
原创粉丝点击