标签:其他 als add oid java string ring 独立 sse
public class FactoryKit {
/**
* Factory Kit:它定义了一个包含不可变内容的工厂,并使用独立的构建器和工厂接口来处理对象的创建。
*/
@Test
public void all() {
final WeaponFactory weaponFactory = WeaponFactory.factory(builder->{
builder.add(WeaponType.SWORD, Sword::new);
builder.add(WeaponType.AXE, Axe::new);
});
final Weapon weapon = weaponFactory.create(WeaponType.SWORD);
assertEquals(Sword.SWORD, weapon.getName());
}
}
enum WeaponType {
SWORD, AXE
}
interface Weapon {
String getName();
}
interface Builder {
void add(WeaponType name, Supplier<Weapon> supplier);
}
interface WeaponFactory {
Weapon create(WeaponType name);
static WeaponFactory factory(Consumer<Builder> consumer) {
final Map<WeaponType, Supplier<Weapon>> map = new HashMap<>();
consumer.accept(map::put);
return name -> map.get(name).get();
}
}
class Axe implements Weapon {
public static final String AXE = "Axe";
@Override
public String getName() {
return AXE;
}
}
class Sword implements Weapon {
public static final String SWORD = "Sword";
@Override
public String getName() {
return SWORD;
}
}
标签:其他 als add oid java string ring 独立 sse
原文地址:https://www.cnblogs.com/zhuxudong/p/10223691.html