工廠模式的三種方式及舉例實現過程
例子:以獲取當前時間 Calendar物件為例 一.靜態工廠 核心:通過靜態方法例項化物件 1建立一個StaticFactory類 public class StaticFactory { public static Calendar getInstance() { return Calendar.getInstance(); } } 2配置xml檔案
<!--Spring中靜態工廠 spring解析方式: 1.當spring容器載入bean標籤時,這時例項化物件 2.spring容器載入工廠類.通過factory-method中標識的方法 例項化物件. 3.spring將id和物件進行儲存.方便物件獲取. --> <!-- 靜態工廠 --> <bean id="calendar1" class="com.jt.manage.factory.StaticFactory" factory-method="getInstance"/> 3測試是否實現 @Test public void testStaticFactory(){ ApplicationContext context = new ClassPathXmlApplicationContext("/spring/factory.xml"); Calendar calendar = (Calendar) context.getBean("calendar1"); System.out.println("獲取時間:"+calendar.getTime()); }
二.例項化工廠 核心:通過物件.方法建立物件 1建立一個InstanceFactory類 public class InstanceFactory { public Calendar getInstance() { return Calendar.getInstance(); } } 2配置xml檔案
<bean id="instanceFactory" class="com.jt.manage.factory.InstanceFactory"/> <bean id="calendar2" factory-bean="instanceFactory" factory-method="getInstance"/> 3測試是否實現
@Test public void testInstanceFactory() { ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("/spring/factory.xml"); Calendar calendar = (Calendar) context.getBean(“calendar2”); System.out.println(“當前時間:”+calendar.getTime()); } 三.Spring工廠模式 核心:通過實現特定的介面,之後回撥例項化物件 1建立一個SpringFactory類 public class SpringFactory implements FactoryBean{ @Override public Calendar getObject() throws Exception { return Calendar.getInstance(); } @Override public Class<?> getObjectType() { return Calendar.class; } @Override public boolean isSingleton() { return false; } } 2配置xml檔案
<!-- spring工廠 -->
<bean id="calendar3" class="com.jt.manage.factory.SpringFactory"/>
3測試是否實現
@Test
public void testSpringFactory() {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("/spring/factory.xml");
Calendar calendar = (Calendar) context.getBean("calendar3");
System.out.println("當前時間:"+calendar.getTime());
}