工厂方法模式的意义是定义一个创建产品对象的工厂接口,将实际创建工作推迟到子类当中。核心工厂类不再负责产品的创建,这样核心类成为一个抽象工厂角色,仅负责具体工厂子类必须实现的接口,这样进一步抽象化的好处是使得工厂方法模式可以使系统在不修改具体工厂角色的情况下引进新的产品。
package org.fanzone.pattern.factoryMethod;
/**
* Title: base
* Description: Product
* Copyright: Copyright (c) 2011
* Create DateTime: Jul 7, 2011 10:35:39 AM
* @author wangmeng
*/
public abstract class Person {
abstract void survive();
}
-----------------------------------------------------------------------
package org.mars.pattern.factoryMethod;
/**
* Title: base
* Description: Creator
* Copyright: Copyright (c) 2011
* Create DateTime: Jul 7, 2011 10:08:42 AM
* @author wangmeng
*/
public interface PersonFactory {
Person producePerson();
}
-------------------------------------------------------------------------
package org.mars.pattern.factoryMethod;
/**
* Title: base
* Description: Concrete Product
* Copyright: Copyright (c) 2011
* Create DateTime: Jul 7, 2011 11:10:23 AM
* @author wangmeng
*/
public class GoodPerson extends Person{
@Override
void survive() {
System.out.println("I'm a good person, but I will be dead one day in the future.");
}
}
-------------------------------------------------------------------------------
package org.mars.pattern.factoryMethod;
/**
* Title: base
* Description: Concrete Product
* Copyright: Copyright (c) 2011
* Create DateTime: Jul 7, 2011 10:56:21 AM
* @author wangmeng
*/
public class BadPerson extends Person{
@Override
void survive() {
System.out.println("Although I'm a bad person, I need food and clothing and shelter and transportation.");
}
}
-------------------------------------------------------------------------------
package org.mars.pattern.factoryMethod;
/**
* Title: base
* Description: Concrete Creator
* Copyright: Copyright (c) 2011
* Create DateTime: Jul 7, 2011 10:26:31 AM
* @author wangmeng
*/
public class GoodPersonFactory implements PersonFactory{
public Person producePerson() {
return new GoodPerson();
}
}
--------------------------------------------------------------------------------------
package org.mars.pattern.factoryMethod;
/**
* Title: base
* Description: Concrete Creator
* Copyright: Copyright (c) 2011
* Create DateTime: Jul 7, 2011 10:54:43 AM
* @author wangmeng
*/
public class BadPersonFactory implements PersonFactory{
public Person producePerson() {
return new BadPerson();
}
}
-----------------------------------------------------------------------------------------
package org.mars.pattern.factoryMethod;
/**
* Title: base
* Description: Test
* Copyright: Copyright (c) 2011
* Create DateTime: Jul 7, 2011 11:22:13 AM
* @author wangmeng
*/
public class Commission {
public static void main(String[] args){
GoodPersonFactory goodPersonFactory = new GoodPersonFactory();
BadPersonFactory badPersonFactory = new BadPersonFactory();
goodPersonFactory.producePerson().survive();
badPersonFactory.producePerson().survive();
}
}