工厂模式只能生产一种商品,如果一个工厂生产多种商品呢?
抽象工厂模式,实现工厂生产多种商品
java代码实例:
- 产品:键盘抽象及实现
// 为了简写所以将抽象及实现放置在一起
public interface KeyBoard {
public String getName();
}
public class AKeyBoard implements KeyBoard {
@Override
public String getName() {
return "this is A keyboard";
}
}
public class BKeyBoard implements KeyBoard {
@Override
public String getName() {
return "this is A keyboard";
}
}
- 产品:鼠标抽象及实现
public interface Mouse {
public String getName();
}
public class AMouse implements Mouse {
@Override
public String getName() {
return "this is A mouse";
}
}
public class BMouse implements Mouse {
@Override
public String getName() {
return "this is B mouse";
}
}
- 抽象工厂
public interface Factory {
KeyBoard createKeyBoard();
Mouse createMouse();
}
- 工厂的实现
public class AFactory implements Factory {
@Override
public KeyBoard createKeyBoard() {
return new AKeyBoard();
}
@Override
public Mouse createMouse() {
return new AMouse();
}
}
public class BFactory implements Factory {
@Override
public KeyBoard createKeyBoard() {
return new BKeyBoard();
}
@Override
public Mouse createMouse() {
return new BMouse();
}
}
- 调用
public class Main {
public static void main(String[] args) {
AFactory aFactory = new AFactory();
System.out.println(aFactory.createKeyBoard().getName());
BFactory bFactory = new BFactory();
System.out.println(bFactory.createMouse().getName());
}
}
使用场景:
- 换肤操作