设计模式之--抽象工厂模式
1,定义:提供一个创建一系列相关或者相互依赖对象的接口,而无需制定它们具体的类;
2,下面是抽象工厂模式的结构图:
3,抽象工厂模式的实现代码:
1),结构图:
2),代码
入口类Main.class:
public class Main {
public static void main(String[] args) {
BreadMaker breadMaker;
PizzaMaker pizzaMaker;
System.out.println("小面的面包店开业了");
System.out.println("顾客要买黑色面包");
IFactory breadFactory = new BlackBreadFactory();
breadMaker = breadFactory.CreateBread();
breadMaker.GetBread();
System.out.println("顾客要黑色巧克力披萨");
pizzaMaker = breadFactory.CreatePizza();
pizzaMaker.GetPizza();
}
}
工厂接口类IFactory.class:
public interface IFactory {
BreadMaker CreateBread();
PizzaMaker CreatePizza();
}
三个工厂类:
BlackBreadFactory.class,HoneyBreadFactory.class,WhiteBreadFactory.class:
public class BlackBreadFactory implements IFactory{
@Override
public BreadMaker CreateBread() {
// TODO Auto-generated method stub
return new BlackBread();
}
@Override
public PizzaMaker CreatePizza() {
// TODO Auto-generated method stub
return new BlackPizza();
}
}
public class HoneyBreadFactory implements IFactory{
@Override
public BreadMaker CreateBread() {
// TODO Auto-generated method stub
return new HoneyBread();
}
@Override
public PizzaMaker CreatePizza() {
// TODO Auto-generated method stub
return new HoneyPizza();
}
}
public class WhiteBreadFactory implements IFactory{
@Override
public BreadMaker CreateBread() {
// TODO Auto-generated method stub
return new WhiteBlead();
}
@Override
public PizzaMaker CreatePizza() {
// TODO Auto-generated method stub
return new WhitePizza();
}
}
两个父类:
BreadMaker,PizzaMaker:
public class BreadMaker {
public void GetBread(){ }
}
public class PizzaMaker {
public void GetPizza(){ }
}
相关子类:
BlackBread,BlackPizza,HoneyBread,HoneyPizza,WhiteBlead,WhitePizza:
public class BlackBread extends BreadMaker{
@Override
public void GetBread() {
// TODO Auto-generated method stub
super.GetBread();
System.out.println("小面做出了黑巧克力面包");
}
}
public class BlackPizza extends PizzaMaker{
@Override
public void GetPizza() {
// TODO Auto-generated method stub
super.GetPizza();
System.out.println("小面做出了黑巧克力披萨");
}
}
public class HoneyBread extends BreadMaker{
@Override
public void GetBread() {
// TODO Auto-generated method stub
super.GetBread();
System.out.println("小面做出了蜂蜜面包");
}
}
public class HoneyPizza extends PizzaMaker{
@Override
public void GetPizza() {
// TODO Auto-generated method stub
super.GetPizza();
System.out.println("小面烤出了蜂蜜披萨");
}
}
public class WhiteBlead extends BreadMaker{
@Override
public void GetBread() {
// TODO Auto-generated method stub
super.GetBread();
System.out.println("小面做出了白色巧克力面包");
}
}
public class WhitePizza extends PizzaMaker{
@Override
public void GetPizza() {
// TODO Auto-generated method stub
super.GetPizza();
System.out.println("小面做出了白巧克力披萨");
}
}
3),运行结果:
3,抽象工厂模式适用情况:
1),一个系列要独立于它的产品创建、组合和表示时;
2),一个系列要由于多个产品系列中的一个来配置时;
3),当要强调一系列相关的产品对象的设计以便进行联合使用时;
4),当要提供一个产品类库,而只有显示它们的接口而不是实现时;