Created
January 20, 2017 10:19
-
-
Save deadcheat/878b77ce69aa65f3d71d9855b032667b to your computer and use it in GitHub Desktop.
FactoryMethodパターンの例を作ろうとして霧の中に迷い込んだ
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.Arrays; | |
import java.util.List; | |
public class Main { | |
public static void main(String[] args) { | |
List<Menu> orders = Arrays.asList(Menu.French, Menu.Sushi, Menu.French, Menu.Sushi); | |
orders.forEach(order -> ChefFactoryManager.build().assignChef(order).cook()); | |
} | |
} | |
class ChefFactoryManager { | |
static ChefFactory cf = null; | |
public static ChefFactory build() { | |
if (cf == null) { | |
cf = new ChefFactory(); | |
} | |
return cf; | |
} | |
} | |
class ChefFactory { | |
private ConcreteFrenchChefCreater french; | |
private ConcreteSushiChefCreater sushi; | |
Chef assignChef(Menu menu) { | |
ChefCreater creator = null; | |
switch (menu) { | |
case Sushi: | |
if (this.sushi == null) { | |
this.sushi = new ConcreteSushiChefCreater(); | |
} | |
creator = this.sushi; | |
break; | |
case French: | |
if (this.french == null) { | |
this.french = new ConcreteFrenchChefCreater(); | |
} | |
creator = this.french; | |
break; | |
} | |
if (creator == null) { | |
return null; | |
} | |
return creator.assign(); | |
} | |
} | |
enum Menu { | |
Sushi, | |
French | |
} | |
// 何料理かわかんないけどキッチンに立っているシェフ達を抽象化したインターフェース | |
interface Chef { | |
void cook(); | |
} | |
// 寿司職人 | |
class ConcreteSushiChef implements Chef { | |
@Override | |
public void cook() { | |
System.out.println("Sushi!!!"); | |
} | |
} | |
// フレンチの鉄人 | |
class ConcreteFrenchChef implements Chef { | |
@Override | |
public void cook() { | |
System.out.println("French!!!"); | |
} | |
} | |
// シェフをアサインするFactoryMethodクラス | |
abstract class ChefCreater { | |
public Chef assign() { | |
Chef chef = callChef(); | |
registerChef(chef); | |
return chef; | |
} | |
protected abstract Chef callChef(); | |
protected abstract void registerChef(Chef chef); | |
} | |
class ConcreteSushiChefCreater extends ChefCreater { | |
@Override | |
protected Chef callChef() { | |
return new ConcreteSushiChef(); | |
} | |
@Override | |
protected void registerChef(Chef chef) { | |
System.out.println("寿司職人がアサインされた!!!"); | |
} | |
} | |
class ConcreteFrenchChefCreater extends ChefCreater { | |
@Override | |
protected Chef callChef() { | |
return new ConcreteFrenchChef(); | |
} | |
@Override | |
protected void registerChef(Chef chef) { | |
System.out.println("フレンチの鉄人がアサインされた!!!"); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment