1.新建一个产品接口 & 工厂接口
public interface Fruit {
void color();//颜色
void shape();//形状
}
public interface Factory {
Fruit createFruit();
}
2.新建产品的实现类
public class Apple implements Fruit {
@Override
public void color() {
System.out.println("苹果颜色:红色");
}
@Override
public void shape() {
System.out.println("苹果形状:圆的");
}
}
public class Banana implements Fruit {
@Override
public void color() {
System.out.println("香蕉颜色:黄色");
}
@Override
public void shape() {
System.out.println("香蕉形状:弯的");
}
}
3.新建工厂的实现类
public class AppleFactory implements Factory {
@Override
public Fruit createFruit() {
return new Apple();
}
}
public class BananaFactory implements Factory {
@Override
public Fruit createFruit() {
return new Banana();
}
}
4.通过不同的工厂类可以获取到不同的产品
public class TestAbstractFactory {
public static void main(String[] args) {
Factory appleFactory = new AppleFactory();
Fruit apple = appleFactory.createFruit();
apple.color();
apple.shape();
Factory bananaFactory = new BananaFactory();
Fruit banana = bananaFactory.createFruit();
banana.color();
banana.shape();
}
}
总结:
往后需要增加任何的类型都只需要增加一个产品类,一个工厂类,然后在客户端调用。
完全符合Java的开闭原则。