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
| public class SimpleFactoryModelTest { public static void main(String[] args) { Factory a = SimpleFactoryModel.getInfo("A"); if (a != null) { a.doSomething(); } Factory b = SimpleFactoryModel.getInfo("B"); if (b != null) { b.doSomething(); } Factory c = SimpleFactoryModel.getInfo("C"); if (c != null) { c.doSomething(); } } }
class SimpleFactoryModel { public static Factory getInfo(String type) { if (type.equals("A")) { return new AFactory(); } else if (type.equals("B")) { return new BFactory(); } else { return null; } } }
abstract class Factory { public abstract void doSomething(); }
class AFactory extends Factory {
@Override public void doSomething() { System.out.println("I am A!"); } }
class BFactory extends Factory {
@Override public void doSomething() { System.out.println("I am B!"); } }
|