标签:
public class ComponentA { // 类的成员直接new出来 ComponentB m_componentB = new ComponentB(); public ComponentA() { } public void Action() { m_componentB.Say(); } static void Main(string[] args) { // 函数的本地变量直接new出来 ComponentA component = new ComponentA(); component.Action(); } } class ComponentB { public void Say() { Console.WriteLine("Hello!"); } }
public class Program { static void Main(string[] args) { Component componentA = Component.makeEmptyComponent(); Component componentB = Component.makeSimpleComponent("Test"); componentA.Say(); componentB.Say(); } } public class Component { private string m_name; private Component (string name, int id, string summary, string description, int priority) { m_name = name; } public void Say() { Console.WriteLine("Hi, my name is {0}", m_name); } public static Component makeEmptyComponent() { return new Component("Empty", 0, "", "", 0); } public static Component makeSimpleComponent(string name) { return new Component(name, 0, "", "", 0); } public static Component makeNormalComponent(string name, int id, string summary) { return new Component(name, id, summary, "", 0); } }
简单工厂
public class Program { static void Main(string[] args) { Component componentA = SimpleFactory.makeComponentA(); Component componentB = SimpleFactory.makeComponentB(); componentA.M(); componentB.M(); } } public static class SimpleFactory { public static Component makeComponentA() { return new ComponentA(); } public static Component makeComponentB() { return new ComponentB(); } } public class Component { public virtual void M() { } } public class ComponentA : Component { public override void M() { Console.WriteLine("This is A"); } } public class ComponentB : Component { public override void M() { Console.WriteLine("This is B"); } }
public class Program { static void Main(string[] args) { ComponentAFactory componentAFactory = new ComponentAFactory(); Component componentA = componentAFactory.makeComponent(); componentA.M(); } } public abstract class Factory { public abstract Component makeComponent(); } public class ComponentAFactory : Factory { public override Component makeComponent() { return new ComponentA(); } } public class ComponentBFactory : Factory { public override Component makeComponent() { return new ComponentB(); } }
public abstract class CarFactory { public abstract Wheel makeWheel(); public abstract Light makeLight(); }
工厂子类去实现创建产品的细节,是不是本质上与工厂方法没什么区别?
标签:
原文地址:http://www.cnblogs.com/dxy1982/p/4389709.html