工厂模式是用来产生普通对象的,随着普通对象类型的增多,使得对应的工厂也会越来越多,那么工厂的管理也会越来越困难,所以就需要用工厂来管理工厂,抽象工厂就是所有工厂的父类,有了父类就可以通过工厂的工厂来统一管理所有的工厂。下面开始使用代码实现。
首先创建颜色接口与颜色对象:
public interface Color {
void draw();
}
public class Blue implements Color {
@Override
public void draw() {
System.out.println("this is blue");
}
}
public class Red implements Color {
@Override
public void draw() {
System.out.println("this is red");
}
}
public class Yellow implements Color {
@Override
public void draw() {
System.out.println("this is yellow");
}
}
创建水果接口与水果对象:
public interface Fruits {
void show();
}
public class Apple implements Fruits {
@Override
public void show() {
System.out.println("this is apple");
}
}
public class Orange implements Fruits {
@Override
public void show() {
System.out.println("this is orange");
}
}
public class Peach implements Fruits{
@Override
public void show() {
System.out.println("this is peach");
}
}
创建抽象工厂、颜色工厂和水果工厂,颜色工厂与水果工厂继承抽象工厂并实现对应的方法:
public abstract class AbstractFactory {
public Fruits getFruits(String fruits){
return null;
}
public Color getColor(String color){
return null;
}
}
public class ColorFactory extends AbstractFactory {
@Override
public Color getColor(String colorString){
switch (colorString){
case "red":
return new Red();
case "blue":
return new Blue();
case "yellow":
return new Yellow();
default:
return null;
}
}
}
public class FruitsFactory extends AbstractFactory {
@Override
public Fruits getFruits(String colorString){
switch (colorString){
case "apple":
return new Apple();
case "orange":
return new Orange();
case "peach":
return new Peach();
default:
return null;
}
}
}
创建工厂的工厂,用来管理所有工厂:
public class Factory {
public static AbstractFactory getFactory(String factoryName) {
switch (factoryName) {
case "color":
return new ColorFactory();
case "fruits":
return new FruitsFactory();
default:
return null;
}
}
public static void main(String[] args) {
AbstractFactory colorFactory = Factory.getFactory("color");
colorFactory.getColor("red").draw();
colorFactory.getColor("blue").draw();
colorFactory.getColor("yellow").draw();
AbstractFactory fruitsFactory = Factory.getFactory("fruits");
fruitsFactory.getFruits("apple").show();
fruitsFactory.getFruits("orange").show();
fruitsFactory.getFruits("peach").show();
}
}
运行结果如下:
可以通过工厂的名字来获取对应的工厂,再使用对象的名字获取到需要的对象。
抽象工厂模式是工厂模式的进一步延伸,工厂模式创建单个类型对象,抽象工厂模式创建多种类型的对象,所以抽象工厂模式与工厂模式的优缺点基本类似。