https://www.runoob.com/design-pattern/abstract-factory-pattern.html
抽象工厂模式:围绕一个超级工厂创建其他工厂。该超级工厂又称为其他工厂的工厂。这种类型的设计模式属于创建型模式,它提供了一种创建对象的最佳方式。
不符合开闭原则在抽象工厂模式中,接口是负责创建一个相关对象的工厂,不需要显式指定它们的类。每个生成的工厂都能按照工厂模式提供对象。
//鼠标产品
public interface Mouse {
void printBrand();
}
//戴尔鼠标
public class DellMouse implements Mouse {
@Override
public void printBrand() {
System.out.println("DELL MOUSE");
}
}
//惠普鼠标
public class HpMouse implements Mouse {
@Override
public void printBrand() {
System.out.println("HP MOUSE");
}
}
//键盘产品
public interface Keyboard {
void printBrand();
}
//戴尔键盘
public class DellKeyboard implements Keyboard {
@Override
public void printBrand() {
System.out.println("DELL KEYBOARD");
}
}
//惠普键盘
public class HpKeyboard implements Keyboard {
@Override
public void printBrand() {
System.out.println("HP KEYBOARD");
}
}
//电脑工厂
public interface PcFactory {
Mouse getMouse();
Keyboard getKeyboard();
}
//戴尔电脑工厂
public class DellPcFatory implements PcFactory {
@Override
public Mouse getMouse() {
return new DellMouse();
}
@Override
public Keyboard getKeyboard() {
return new DellKeyboard();
}
}
//惠普电脑工厂
public class HpPcFactory implements PcFactory {
@Override
public Mouse getMouse() {
return new HpMouse();
}
@Override
public Keyboard getKeyboard() {
return new HpKeyboard();
}
}
//测试
@SpringBootApplication
public class App {
public static void main(String[] args) {
SpringApplication.run(App.class);
PcFactory pcFactory = new HpPcFactory();
pcFactory.getMouse().printBrand();
pcFactory.getKeyboard().printBrand();
}
}