设计模式-工厂模式
2018-03-19 本文已影响0人
ShenHehe
1. 工厂模式
假如有家食品厂在生产食物,先创建一个接口
public interface Food {
void make();
}
这食品厂能制造饮料(具体产品类)
public class Drinks implements Food {
@Override
public void make() {
System.out.println("生产饮料");
}
}
也可以制造饼干(具体产品类)
public class Biscuits implements Food {
@Override
public void make() {
// TODO Auto-generated method stub
System.out.println("生产饼干");
}
}
开工厂为了接单赚钱嘛,这里相当于订单,当别人下了订单类型,生产对应的产品(工厂类)
public class FoodFactory {
public static final int DRINKS = 0;
public static final int BISCUITS = 1;
public Food getPlayer(int type) {
switch (type) {
case DRINKS:
return new Drinks();
case BISCUITS:
return new Biscuits();
default:
return null;
}
}
}
接到饮料单子,开始生产饮料了~
public static void main(String[] args) {
FoodFactory factory = new FoodFactory();
Food food = factory.getPlayer(FoodFactory.DRINKS);
food.make();
}
2. 工厂方法模式
先写一个食品厂
public interface FoodFactory {
public Food getFood();
}
这个食品厂的饮料生产线
public class DrinksFactory implements FoodFactory{
@Override
public Food getFood() {
// TODO Auto-generated method stub
return new Drinks();
}
还有饼干类的生产线
public class BiscuitsFactory implements FoodFactory{
@Override
public Food getFood() {
// TODO Auto-generated method stub
return new Biscuits();
}
}
接到哪种订单就new哪种类型的生产线就行啦~
public static void main(String[] args) {
// TODO Auto-generated method stub
FoodFactory factory = new BiscuitsFactory();
Food food = factory.getFood();
food.make();
}
3. 抽象工厂
假设现在有家衣服店在卖衣服
先定义衣服款式类型
public interface Style {
void type();
}
public class LongSleeve implements Style {
@Override
public void type() {
System.out.println("长袖");
}
}
public class ShortSleeve implements Style {
@Override
public void type() {
System.out.println("短袖");
}
}
还有衣服的颜色
public interface Color {
void fill();
}
public class Red implements Color {
@Override
public void fill() {
System.out.println("红色");
}
}
public class Blue implements Color {
@Override
public void fill() {
System.out.println("蓝色");
}
}
定义这件adidas的款式以及颜色
public class AdidasFactory implements AbstractFactory{
@Override
public Style getStyle() {
return new LongSleeve();
}
@Override
public Color getColor() {
return new Red();
}
}
还有特步的款式颜色
public class XtepFactory implements AbstractFactory {
@Override
public Style getStyle() {
return new ShortSleeve();
}
@Override
public Color getColor() {
return new Blue();
}
}
测试
public static void main(String[] args) {
AbstractFactory adidas = new AdidasFactory();
adidas.getStyle().type();
adidas.getColor().fill();
AbstractFactory xtep = new XtepFactory();
xtep.getStyle().type();
xtep.getColor().fill();
}