您的位置:首页 > 其它

设计模式-----Simple Factory(简单工厂模式)

2012-09-09 00:00 645 查看
UML:



/**
* Product Interface
* @author  MC
*
*/
public interface Product {

/**
* Get Product Name
*/
public String getName();

}

/**
* Concrete Product A
* @author  MC
*
*/
public class ProductA implements Product{

public String getName() {
// TODO Auto-generated method stub
return "I am ProductA.";
}

}

/**
* Concrete Product B
* @author  MC
*
*/
public class ProductB implements Product{

public String getName() {
// TODO Auto-generated method stub
return "I am ProductB.";
}

}

/**
* Factory Class
* @author  MC
*
*/
public class ProductCreatorFactory {

public static Product createProduct(String type) {

if(type.equalsIgnoreCase("A")){
return new ProductA();
}
if(type.equalsIgnoreCase("B")){
return new ProductB();
}

return null;
}

}

public class SimpleFactoryTest {

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Product productA=ProductCreatorFactory.createProduct("A");
System.out.println(productA.getName());

Product productB=ProductCreatorFactory.createProduct("B");
System.out.println(productB.getName());

}

}


Console:

I am ProductA.
I am ProductB.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息