工厂模式分为: 简单工厂,基本工厂,抽象工厂
简单工厂模式
用户给一个值,工厂返回相应的对象。
DEMO
public interface Milk {
String getMilk();
}
public class MengNiu implements Milk {
@Override
public String getMilk() {
return "蒙牛";
}
}
public class YiLi implements Milk {
@Override
public String getMilk() {
return "伊利";
}
}
public class SimpleFactory {
public Milk getMilk(String name){
if ("mengniu".equals(name)){
return new MengNiu();
}
if ("yili".equals(name)){
return new YiLi();
}
if ("sanlu".equals(name)){
return new SanLv();
}
return null;
}
}
普通工厂模式
需要哪个自己new一个对应的工厂。
DEMO
public interface Factory {
Milk getMilk();
}
public class MengNiuFactory implements Factory {
@Override
public Milk getMilk() {
return new MengNiu();
}
}
public class YiLiFactory implements Factory {
@Override
public Milk getMilk() {
return new YiLi();
}
}
public class FactoryTest {
public static void main(String[] args){
Factory factory=new YiLiFactory();
factory.getMilk().getMilk();
}
}
抽象工厂
抽象工厂,用户只需要自己选择即可。不用关心任何其他的。
DEMO
public abstract class AbstractFactory {
//可以执行一些所有工厂统一标准
abstract Milk getYiLi();
abstract Milk getSanLu();
abstract Milk getMengNiu();
}
public class MilkFactory extends AbstractFactory {
Milk getYiLi(){
return new YiLiFactory().getMilk();
}
Milk getSanLu(){
//这里都可以直接new SanLu();
return new SanLuFactory().getMilk();
}
Milk getMengNiu(){
return new MengNiuFactory().getMilk();
}
}