抽象工厂模式:提供一个创建一系列相关或相互依赖对象的接口,而无需指定它们具体的类
下面是一个解释抽象工厂的小例子,定义了三类产品,分别为Fruit,ElecProduct,Traffic以及它们各自的产品
首先是Fruit
package com.lamp.factory.abstractfactory;
public abstract class Fruit {
public abstract void eat();
}
package com.lamp.factory.abstractfactory;
public class Apple extends Fruit{
@Override
public void eat() {
System.out.println("吃的是水果");
}
}
package com.lamp.factory.abstractfactory;
public class Banana extends Fruit{
@Override
public void eat() {
System.out.println("吃的是香蕉");
}
}
然后是ElecProduct
package com.lamp.factory.abstractfactory;
public abstract class ElecProduct {
public abstract void getName();
}
package com.lamp.factory.abstractfactory;
public class Computer extends ElecProduct{
@Override
public void getName() {
System.out.println("使用的是电脑");
}
}
package com.lamp.factory.abstractfactory;
public class Mobile extends ElecProduct{
@Override
public void getName() {
System.out.println("使用的是手机");
}
}
最后是Traffic
package com.lamp.factory.abstractfactory;
public abstract class Traffic {
public abstract void run();
}
package com.lamp.factory.abstractfactory;
public class Plane extends Traffic{
@Override
public void run() {
System.out.println("飞机在天上飞");
}
}
package com.lamp.factory.abstractfactory;
public class Car extends Traffic{
@Override
public void run() {
System.out.println("开的是car");
}
}
接着定义了一个总的抽象工厂,生产三类产品,具体生产的产品由其工厂类去决定
package com.lamp.factory.abstractfactory;
public abstract class MyAbstractFactory {
public abstract Traffic createTraffic();
public abstract ElecProduct createElecProduct();
public abstract Fruit createFruit();
}
第一个工厂类为DefaultFactory
package com.lamp.factory.abstractfactory;
/**
* 默认工厂生产的是car,Computer,Apple
*
*/
public class DefaultFactory extends MyAbstractFactory {
@Override
public Traffic createTraffic() {
return new Car();
}
@Override
public ElecProduct createElecProduct() {
return new Computer();
}
@Override
public Fruit createFruit() {
return new Apple();
}
}
另一个工厂类为NewFactory
package com.lamp.factory.abstractfactory;
/**
*
* 新工厂生产的是Plane,Mobile,Banana
*
*/
public class NewFactory extends MyAbstractFactory {
@Override
public Traffic createTraffic() {
return new Plane();
}
@Override
public ElecProduct createElecProduct() {
return new Mobile();
}
@Override
public Fruit createFruit() {
return new Banana();
}
}
最后进行测试
package com.lamp.factory.abstractfactory;
/**
*
* 抽象工厂的优点在于当你的工厂发生改变的时候,其不同类型对应的产品也会自动发生改变,就像常见的换肤效果
* 而且对已经存在的产品类型添加产品的时候也方便
* 当然如果要添加新的产品类型,这时需要在总的抽象工厂中添加新的类型以及在相应工厂中做相应修改,这也是抽象
* 工厂不足的地方
*
*/
public class Test {
public static void main(String[] args) {
//MyAbstractFactory factory = new DefaultFactory();
MyAbstractFactory factory = new NewFactory();
ElecProduct e = factory.createElecProduct();
e.getName();
Fruit f = factory.createFruit();
f.eat();
Traffic t = factory.createTraffic();
t.run();
}
}