








VS 2008
工厂方法模式提供创建一系列属于同一产品体系的类的创建方法。并且,有别于一般的简单工厂,工厂方法模式创建产品由子类来完成。这样增加新的产品不需要修改原来的代码,只需要相应增加一个新的工厂子类。
1. 模式UML图

2. 应用
程序中需要使用到不同的交通工具,将交通工具的行为抽象为一个接口,那么这些交通工具就形成了一个有共同行为的产品体系。根据工厂方法模式的思想,为产品的创建相应的建立一套工厂体系。

ITransportation.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DesignPattern.FactoryMethod.BLL {

public interface ITransportation {

void Run();
}
}

Car.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DesignPattern.FactoryMethod.BLL {

public class Car : ITransportation {
ITransportation Members
}
}

Plane.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DesignPattern.FactoryMethod.BLL {

public class Plane : ITransportation {
ITransportation Members
}
}

ITransportationFactory.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DesignPattern.FactoryMethod.BLL {
public interface ITransportationFactory {

ITransportation Create();
}
}

CarFactory.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DesignPattern.FactoryMethod.BLL {

public class CarFactory : ITransportationFactory {
ITransportationFactory Members
}
}

PlaneFactory.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DesignPattern.FactoryMethod.BLL {

public class PlaneFactory : ITransportationFactory {
ITransportationFactory Members
}
}

Client
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DesignPattern.FactoryMethod.BLL;

namespace DesignPattern.FactoryMethod {
class Program {
static void Main(string[] args) {

ITransportationFactory carFactory = new CarFactory();
ITransportation car = carFactory.Create();
car.Run();

ITransportationFactory planeFactory = new PlaneFactory();
ITransportation plane = planeFactory.Create();
plane.Run();
}
}
}

Output

此内容由惯性聚合(RSS阅读器)自动聚合整理,仅供阅读参考。 原文来自 — 版权归原作者所有。