- 定义:为创建一组相关或相互依赖的对象提供一个借口,而且无需指定他们的具体类;
- 优点:使用抽象工厂来创建需要的对象,不需要知道具体的实现是谁,不用关心对象是如何创建出来的,只需知道工厂类是谁就能创建出一个对象;
- 缺点:如果需要给整个产品族添加一个新的产品,那么就需要修改抽象工厂,这样就会导致修改所有的工厂实现类;
上代码
/*** 手机电池接口*/
public interface Cell {void cellCapacity();//电池容量
}
/*** 华为的接口*/
public interface HuaWei {void phoneColor();//手机颜色void phonePrice();//手机价格void phoneSize();//手机尺寸
}
/*** 华为工厂的接口*/
public interface HuaWeiFactory {HuaWei createHuaWei();//创建华为手机Cell createCell();//创建电池
}
/*** Mate20手机的产品类*/
public class Mate20 implements HuaWei {public Mate20() {this.phoneColor();this.phonePrice();this.phoneSize();}@Overridepublic void phoneColor() {System.out.println("Mate20黑色");}@Overridepublic void phonePrice() {System.out.println("Mate20价格是5000");}@Overridepublic void phoneSize() {System.out.println("Mate20尺寸是6.5英寸");}
}
public class Mate20Cell implements Cell {public Mate20Cell() {this.cellCapacity();}@Overridepublic void cellCapacity() {System.out.println("Mate20的电池电量是3000毫安");}
}
/*** 生产华为Mate20的工厂*/
public class Mate20Factory implements HuaWeiFactory {public Mate20Factory(){this.createHuaWei();this.createCell();}@Overridepublic HuaWei createHuaWei() {return new Mate20();}@Overridepublic Cell createCell() {return new Mate20Cell();}
}
public class P20 implements HuaWei {public P20() {this.phoneColor();this.phonePrice();this.phoneSize();}@Overridepublic void phoneColor() {System.out.println("P20的颜色是蓝色");}@Overridepublic void phonePrice() {System.out.println("P20的价格是2000");}@Overridepublic void phoneSize() {System.out.println("P20的尺寸是5.5英寸");}
}
public class P20Cell implements Cell {public P20Cell() {this.cellCapacity();}@Overridepublic void cellCapacity() {System.out.println("华为P20电池是1900毫安");}
}
/*** 华为P20的生产工厂*/
public class P20Factory implements HuaWeiFactory {public P20Factory(){this.createHuaWei();this.createCell();}@Overridepublic HuaWei createHuaWei() {return new P20();}@Overridepublic Cell createCell() {return new P20Cell();}
}
public class MainActivity extends Activity {@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);createMate20();createP20();}private void createMate20() {System.out.println("生产华为Mate20");
// HuaWeiFactory factory = new Mate20Factory();new Mate20Factory();System.out.println("----------华丽丽的分界线----------------");}private void createP20() {System.out.println("生产华为P20");
// HuaWeiFactory factory = new P20Factory();new P20Factory();}
}
以上就是一个简单的抽象工厂模式了,欢迎大家指正...