之前学过了简单工厂模式,工厂方法模式,简单工厂在创建的时候,需要传入一个识别符,然后返回相应的实例。而工厂方法在需要的时候,创建相应的工厂类,获得相应的实例。
抽象工厂模式(Abstract Factory):提供一个创建一系列相关或互相依赖的接口,而无需指定它们具体的类。
看看UML类图
基本代码
/// <summary>
/// 抽象产品A
/// </summary>
public abstract class Car
{
public abstract void Run();
}
/// <summary>
/// 抽象产品B
/// </summary>
public interface IBus
{
void Run();
}
/// <summary>
/// 实体产品A1
/// </summary>
public class BMWCar:Car
{
public override void Run()
{
Console.WriteLine("宝马轿车在行驶!");
}
}
/// <summary>
/// 实体产品A2
/// </summary>
public class BenzCar:Car
{
public override void Run()
{
Console.WriteLine("奔驰轿车在行驶!");
}
}
/// <summary>
/// 实体产品B1
/// </summary>
public class BMWBus : IBus
{
public void Run()
{
Console.WriteLine("宝马大汽车");
}
}
/// <summary>
/// 实体产品B2
/// </summary>
public class BenzBus : IBus
{
public void Run()
{
Console.WriteLine("奔驰大汽车");
}
}
/// <summary>
/// 抽象工厂
/// </summary>
public abstract class AbstractFactory
{
public static AbstractFactory CreateFactory(string strType)
{
AbstractFactory factory = null;
switch (strType)
{
case "BMW":
factory = new BMWFactory();
break;
case "Benz":
factory = new BenzFactory();
break;
}
return factory;
}
/// <summary>
/// 抽象方法 创建Car对象
/// </summary>
/// <returns></returns>
public abstract Car CreateCar();
/// <summary>
/// 创建BUS
/// </summary>
/// <returns></returns>
public abstract IBus CreateBus();
}
/// <summary>
/// 实体工厂1
/// </summary>
public class BMWFactory:AbstractFactory
{
public override Car CreateCar()
{
return new BMWCar();
}
public override IBus CreateBus()
{
return new BMWBus();
}
}
/// <summary>
/// 实体工厂2
/// </summary>
public class BenzFactory : AbstractFactory
{
public override Car CreateCar()
{
return new BenzCar();
}
public override IBus CreateBus()
{
return new BenzBus();
}
}
客户端
package com.abings.abstractfactory;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import com.abings.abstractfactory.AbstractFactory.Bus;
import com.abings.abstractfactory.AbstractFactory.Car;
import com.abings.abstractfactory.AbstractFactory.IFactory;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//宝马工厂
IFactory iFactory = IFactory.createFactory("Bwm");
//奔驰工厂
IFactory iFactory1 = IFactory.createFactory("Benz");
//宝马系列的公交和汽车
Bus bus = iFactory.createBus();
Car car = iFactory.createCar();
//出厂测试
bus.run();
car.run();
//奔驰系列
Bus bus1 = iFactory1.createBus();
Car car1 = iFactory1.createCar();
//出厂测试
car1.run();
bus1.run();
}
}
使用过程我们发现,其实ProduxtA1和ProductB1是一个系列。需要用一个工厂来统一它们的实例。所有工厂类这边有个对应的工厂生产类。
代码git:https://github.com/SingleShu/AbstractFactoryModel