设计模式 - 工厂模式
简单工厂模式
package com.lushwe.pattern.factory;
/**
* @Author Jack
* @Description
* @Date Create in 2018/6/21 14:43
*/
public interface Milk {
String getName();
}
public class SimpleFactory {
public Milk getMilk(String name) {
if ("telunsu".equalsIgnoreCase(name)) {
return new Telunsu();
} else if ("mengniu".equalsIgnoreCase(name)) {
return new Mengniu();
}
throw new IllegalArgumentException("name[" + name + "] is invalid");
}
}
// 具体角色1
public class Mengniu implements Milk {
@Override
public String getName() {
return "蒙牛";
}
}
// 具体角色2
public class Telunsu implements Milk {
public String getName() {
return "特仑苏";
}
}
public class SimpleFactoryTest {
public static void main(String[] args) {
SimpleFactory factory = new SimpleFactory();
Milk telunsu = factory.getMilk("telunsu");
Milk mengniu = factory.getMilk("mengniu");
System.out.println("telunsu.name = " + telunsu.getName());
System.out.println("mengniu.name = " + mengniu.getName());
}
}
milk.name = 特仑苏
milk.name = 蒙牛
工厂方法模式
public interface Factory {
Milk getMilk();
}
// 具体工厂1
public class MengniuFactory implements Factory {
@Override
public Milk getMilk() {
return new Mengniu();
}
}
// 具体工厂2
public class TelunsuFactory implements Factory {
@Override
public Milk getMilk() {
return new Telunsu();
}
}
public class FuncFactoryTest {
public static void main(String[] args) {
Factory factory;
Milk milk;
factory = new TelunsuFactory();
milk = factory.getMilk();
System.out.println("milk1.name = " + milk.getName());
factory = new MengniuFactory();
milk = factory.getMilk();
System.out.println("milk2.name = " + milk.getName());
}
}
milk1.name = 特仑苏
milk2.name = 蒙牛
抽象工厂模式
public abstract class AbstractFactory {
public abstract Milk getTelunsu();
public abstract Milk getMengniu();
}
public class MilkFactory extends AbstractFactory {
@Override
public Milk getTelunsu() {
return new Telunsu();
}
@Override
public Milk getMengniu() {
return new Mengniu();
}
}
public class AbstractFactoryTest {
public static void main(String[] args) {
MilkFactory factory = new MilkFactory();
Milk telunsu = factory.getTelunsu();
Milk mengniu = factory.getMengniu();
System.out.println(telunsu.getName());
System.out.println(mengniu.getName());
}
}
特仑苏
蒙牛
网友评论