java实现
产品抽象类
public abstract class Product {
public void method1(){}
public abstract void method2();
}
产品实现类
public class CreateProduct1 extends Product {
@Override
public void method2() {
}
}
public class CreateProduct2 extends Product {
@Override
public void method2() {
}
}
工厂抽象类
public abstract class AbstractFaculty {
public abstract <T extends Product> T createProduct(Class<T> clazz);
}
工厂实现类
public class ProduceFactory extends AbstractFaculty {
@Override
public <T extends Product> T createProduct(Class<T> clazz) {
Product product = null;
try{
product = (Product) Class.forName(clazz.getName()).newInstance();
}catch (Exception e){
}
return (T) product;
}
}
场景测试类
public class Client {
public static void main(String[] args){
AbstractFaculty faculty = new ProduceFactory();
Product createProduct1 = faculty.createProduct(CreateProduct1.class);
Product createProduct2 = faculty.createProduct(CreateProduct2.class);
}
}
以上是常规情形的工厂方法模式
当对工厂类只需要一个不必抽象时,可以将工厂方法直接声明一个静态方法
public class ProductFacultyStatic {
public static <T extends Product> T createProduct(Class<T> clazz) {
Product product = null;
try{
product = (Product) Class.forName(clazz.getName()).newInstance();
}catch (Exception e){
}
return (T) product;
}
}
当每个产品对象的创建非常复杂时,可以为每个产品类分别对应一个工厂类,这样的优点是各个功能模块都隔离,我缺点是类的数量增加,不便于维护
public class CreateProduct1Faculty extends AbstractFaculty {
@Override
public <T extends Product> T createProduct(Class<T> clazz) {
return (T) new CreateProduct1();
}
}
当一个对象的创建消耗很大资源时,需要重用,可以将其缓存到map中,当下次使用时,不必创建,使用上次创建的
public class ProductFacultyStatic {
private static Map<String,Product> productMap = new HashMap<>();
public static synchronized Product createProduct(String type){
Product product = null;
if(productMap.containsKey(type)){
product = productMap.get(type);
}else{
if("Product1".equals(type)){
product = new CreateProduct1();
}else{
product = new CreateProduct2();
}
}
return product;
}
}
php实现
abstract class Product
{
public function method1(){}
public abstract function method2();
}
class Product1 extends Product
{
public function method2()
{
echo "product1 method2 \n";
}
}
class Product2 extends Product
{
public function method2()
{
echo "product2 method2 \n";
}
}
abstract class AbsFactory
{
public abstract function createProduct($productClassName);
}
class ProductFactory extends AbsFactory
{
public function createProduct($productClassName)
{
return new $productClassName;
}
}
$factory = new ProductFactory;
$product = $factory->createProduct('Product1');
$product->method2();
$product = $factory->createProduct('Product2');
$product->method2();