抽象工厂模式跟工厂方式模式类似,不同的是工厂方式模式生产的是一个抽象的产品,而抽象工厂模式生产的是多个抽象的产品。
标准类图
抽象工厂模式:
顶层抽象产品类:
public interface Product {
String getInfo();
}
第二层抽象产品(抽象出两个不同的产品)
public interface Phone extends Product{
public void call();
}
public interface Pad extends Product{
public void watchWithBigScreen();
}
具体的产品:
public class GalaxyS5 implements Phone{
@Override
public String getInfo() {
return "this is galaxy s5";
}
@Override
public void call() {
System.out.println("galaxy s5 can be called");
}
}
public class Xiaomi2S implements Phone{
@Override
public String getInfo() {
return "this is xiaomi phone";
}
@Override
public void call() {
System.out.println("xiaomi 2s can be called");
}
}
public class SamSungPad implements Pad {
@Override
public void watchWithBigScreen() {
System.out.println("Samsung pad can watch movies using big screen");
}
@Override
public String getInfo() {
return "this is Samsung pad";
}
}
public class XiaomiPad implements Pad {
@Override
public String getInfo() {
return "this is xiaomi pad";
}
@Override
public void watchWithBigScreen() {
System.out.println("xiaomi pad can watch movies using big screen");
}
}
创建工厂:
public interface IFactory {
Phone createPhone();
Pad createPad();
}
具体的工厂:
public class SamSungFactory implements IFactory{
@Override
public Phone createPhone() {
return new GalaxyS5();
}
@Override
public Pad createPad() {
return new SamSungPad();
}
}
public class XiaomiFactory implements IFactory {
@Override
public Phone createPhone() {
return new Xiaomi2S();
}
@Override
public Pad createPad() {
return new XiaomiPad();
}
}
场景类:
public class Client {
public static void main(String[] args) throws Exception{
IFactory samsungFactory = new SamSungFactory();
IFactory xiaomiFactory = new XiaomiFactory();
Phone galaxyS5 = samsungFactory.createPhone();
Pad samsungPad = samsungFactory.createPad();
Phone xiaomi2s = xiaomiFactory.createPhone();
Pad xiaomiPad = xiaomiFactory.createPad();
System.out.println(galaxyS5.getInfo());
System.out.println(samsungPad.getInfo());
System.out.println(xiaomi2s.getInfo());
System.out.println(xiaomiPad.getInfo());
galaxyS5.call();
xiaomi2s.call();
samsungPad.watchWithBigScreen();
xiaomiPad.watchWithBigScreen();
}
}