23種設計模式及簡單程式碼
阿新 • • 發佈:2019-01-25
<pre name="code" class="java">public abstract class Animal{}; public class Cat extends Animal{}; public class Dog extends Animal{}; public abstract class Fruit{}; public class Apple extends Fruit{}; public class Orange extends Fruit{}; public abstract class Factory{ public abstract Animal getCat(); public abstract Animal getDog(); public abstract Fruit getApple(); public abstract Fruit getOrange(); } public class AnimalFactory extends Factory{ public Animal getCat(){ return new Cat(); } public Animal getDog(){ return new Dog(); } } public class FruitFactory extends Factory{ public Fruit getApple(){ return Apple(); } public Fruit getOrange(){ return Orange(); } } public class TestFactory{ public static void main(){ Factory af = new AnimalFactory(); Animal cat = af.getCat(); Animal dog = af.getDog(); Factory ff = new FruitFactory(); Fruit apple = ff.getApple(); ... } }