java筆試--設計模式
阿新 • • 發佈:2018-11-05
單列模式
public class Singleton { /* * private static Singleton instance; private Singleton(){ * * } public static Singleton getInstance(){ if(instance==null){ synchronized * (Singleton.class) { if(instance==null){ instance=new Singleton(); } } } * return instance; } */ private static Singleton instance; private Singleton() { } public static Singleton getInstance() { if (instance == null) { synchronized (Singleton.class) { if (instance == null) { instance = new Singleton(); } } } return instance; } }
interface Animal { public void say(); } class Cat implements Animal { public void say() { System.out.print("貓說話"); } } class Mouse implements Animal { public void say() { System.out.print("老鼠說話"); } } class Factory { public static Animal getInstance(String className) { Animal animal = null; if ("Cat".equals(className)) { animal = new Cat(); } if ("Mouse".equals(className)) { animal = new Mouse(); } return animal; } }