工厂模式:利用工厂来创建相应的类
public class App {
public static void main(String[] args) {
WeaponFactory factory=WeaponFactory.factory(builder -> {
builder.add(WeaponType.SWORD,Sword::new);
builder.add(WeaponType.AXE,Axe::new);
builder.add(WeaponType.SPEAR,Spear::new);
builder.add(WeaponType.BOW,Bow::new);
});
Weapon axe=factory.create(WeaponType.AXE);
System.out.println(axe.toString());
}
}
public class Axe implements Weapon {
@Override
public String toString() {
return "Axe";
}
}
public class Bow implements Weapon {
@Override
public String toString() {
return "Bow";
}
}
public interface Builder {
void add(WeaponType name, Supplier<Weapon> supplier);
}
public class Spear implements Weapon {
@Override
public String toString() {
return "Spear";
}
}
public class Sword implements Weapon {
@Override
public String toString() {
return "Sword";
}
}
public interface Weapon {
}
public interface WeaponFactory {
Weapon create(WeaponType name);
static WeaponFactory factory(Consumer<Builder> consumer){
Map<WeaponType,Supplier<Weapon>> map=new HashMap<>();
consumer.accept(map::put);
return name->map.get(name).get();
}
}
public enum WeaponType {
SWORD, AXE, BOW, SPEAR
}
代码解析:这里主要用到了java8的一些功能,如:Consumer and Supplier
可以参照我的博客http://blog.csdn.net/u011747152/article/details/78202994
这里参数传入到WeaponFactory
// Consumer<Builder> consumer=builder -> {
// builder.add(WeaponType.SWORD,Sword::new);
// builder.add(WeaponType.AXE,Axe::new);
// builder.add(WeaponType.SPEAR,Spear::new);
// builder.add(WeaponType.BOW,Bow::new);
// };
public interface WeaponFactory {
Weapon create(WeaponType name);
static WeaponFactory factory(Consumer<Builder> consumer){
Map<WeaponType,Supplier<Weapon>> map=new HashMap<>();//构造一个空map
consumer.accept(map::put);//这里调用map的put方法因为map刚好是参数传入的格式,所以就把参 数全存到map里了
return name->map.get(name).get();//map.get(name)是一个Supplier<Weapon>
}
}