一、定義一個接口java
public interface MyCalendar { public static final int CALENDAR_LUNAR = 1; public static final int CALENDAR_GREGORIAN = 2; public abstract String getTime(); }
二、寫兩個實現ide
public class GregorianCalendar implements MyCalendar{ @Override public String getTime() { return "如今是公曆時間:Xxx"; } }
public class LunarCalendar implements MyCalendar{ @Override public String getTime() { return "如今是農曆時間:Yyy"; } }
三、寫一個工廠code
public class MyCalendarFactory { public static MyCalendar getCalendar(int type) { if(type == MyCalendar.CALENDAR_LUNAR){ return new LunarCalendar(); }else if (type == MyCalendar.CALENDAR_GREGORIAN) { return new GregorianCalendar(); } throw new RuntimeException("擦擦擦..."); } }
四、客戶端接口
public class Client { public static void main(String[] args) { MyCalendar mc1 = MyCalendarFactory.getCalendar(MyCalendar.CALENDAR_GREGORIAN); System.out.println(mc1.getTime()); MyCalendar mc2 = MyCalendarFactory.getCalendar(MyCalendar.CALENDAR_LUNAR); System.out.println(mc2.getTime()); } }