工厂模式的介绍 http://www.runoob.com/design-pattern/factory-pattern.html
最关键的是抽象出一个接口,然后创建实现接口的实体类,接着创建一个工厂,生成基于给定信息的实体类的对象。使用该工厂,通过传递类型信息来获取实体类的对象。
因为本人最喜欢刘亦菲,刘诗诗,舒畅这三个女明星,所以很形象的把工厂模式表现出来。
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package dict1;
/**
*
* @author lenovo
*/
interface Actress
{
public void sleep();
}
class LiuYiFei implements Actress
{
@Override
public void sleep() {
System.out.println("睡刘亦菲。");
}
}
class LiuShiShi implements Actress
{
@Override
public void sleep() {
System.out.println("睡刘诗诗。");
}
}
class ShuChang implements Actress
{
@Override
public void sleep() {
System.out.println("睡舒畅。");
}
}
class Factory {
public static Actress fun(String className)
{
if("LiuYiFei".equals(className))
return new LiuYiFei();
if("LiuShiShi".equals(className))
return new LiuShiShi();
if("ShuChang".equals(className))
return new ShuChang();
return null;
}
}
public class Dict1 {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
String[] str={"LiuYiFei","LiuShiShi","ShuChang"};
for(int i=0;i<3;i++)
{
Actress f = Factory.fun(str[i]);
f.sleep();
}
}
}