一、抽象工厂的特点
二、需求:一个制造工厂同时生成汽车和手表两种产品,工厂可定制生产宝马汽车、奔驰汽车、浪琴手表、劳力士手表,向客户出售指定产品
创建步骤
1、抽象需要生产的产品
/**
*抽象产品
*/
public interface Product {
//产品出售
void sellProduct();
}
2、抽象生产工厂
/**
* 抽象产品
*/
public interface AbstractFactory {
//生产特定产品
Product product(String type) throws Exception;
}
3、具体产品
/**
* 宝马车
*/
public class BaoMaCar implements Product{
@Override
public void sellProduct() {
System.out.println("sell-------->BaMaCar");
}
}
/**
* 奔驰车
*/
public class BenChiCar implements Product{
@Override
public void sellProduct() {
System.out.println("sell-------->BenChiCar");
}
}
/**
* 劳力士表
*/
public class LaoLiShiWacth implements Product {
@Override
public void sellProduct() {
System.out.println("sell----->LaoLiShiWacth");
}
}
/**
* 浪琴表
*/
public class LangQinWatch implements Product{
@Override
public void sellProduct() {
System.out.println("sell------>LiangQinWatch");
}
}
4、具体的手表创建工厂、汽车创建工厂
public enum ProductType {
LangQin("LangQinWatch"), LaoLishi("LaoLiShiWacth"), BenChi("BenChiCar"), DaZhong("DaZhongCar"), BaoMa("BaMaCar");
private String type;
ProductType(String type) {
this.type = type;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
}
/**
* 手表生产工厂
*/
public class WatchFactory implements AbstractFactory {
@Override
public Product product(String type) throws Exception {
if (ProductType.LangQin.getType().equals(type)) {
return new LangQinWatch();
} else if (ProductType.LaoLishi.getType().equals(type)) {
return new LaoLiShiWacth();
}
throw new Exception("请填写有效的手表产品名称");
}
}
/**
* 汽车生产工厂
*/
public class CarFactory implements AbstractFactory{
@Override
public Product product(String type) throws Exception {
if(ProductType.BaoMa.getType().equals(type)) {
return new BaoMaCar();
}else if(ProductType.BenChi.getType().equals(type)){
return new BenChiCar();
}
throw new Exception("请填写有效的汽车产品名称");
}
}
5、生产测试
public class FactoyTest {
public static void main(String[] args) {
try {
Product product= new CarFactory().product(ProductType.BaoMa.getType());
product.sellProduct();
} catch (Exception e) {
e.printStackTrace();
}
try {
Product product = new WatchFactory().product(ProductType.LaoLishi.getType());
product.sellProduct();
} catch (Exception e) {
e.printStackTrace();
}
}
}
运行打印:
sell-------->BaMaCar
sell----->LaoLiShiWacth