オブジェクト指向、エンジンのたとえ
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 |
import java.util.*; interface Engine { public void boot(); public void stop(); } class EngineFigurative implements Engine { private String maker; public EngineFigurative(String maker) { this.maker = maker; } public String getMaker() { return this.maker; } public void boot() { System.out.println(this.maker + " boot()"); } public void stop() { System.out.println(this.maker + " stop()"); } } class EngineFactory { public Engine generate(String maker) { Engine engine = new EngineFigurative(maker); return engine; } } class EngineHandler { public void bootAll(List<Engine> engines) { for (Engine engine : engines) { engine.boot(); } } public void stopAll(List<Engine> engines) { for (Engine engine : engines) { engine.stop(); } } } public class Main { public static void main(String[] args) throws Exception { EngineFactory ef = new EngineFactory(); EngineHandler eh = new EngineHandler(); List<Engine> engineList = new ArrayList<>(); engineList.add(ef.generate("ホンダ")); engineList.add(ef.generate("Nissan")); engineList.add(ef.generate("TOYOTA")); eh.bootAll(engineList); eh.stopAll(engineList); } } |
1 2 3 4 5 6 |
ホンダ boot() Nissan boot() TOYOTA boot() ホンダ stop() Nissan stop() TOYOTA stop() |