简单工厂模式的作用就是定义一个用于创建对象的接口
在简单工厂模式中,一个工厂类处于对产品类实例化调用的中心位置上,它决定那一个产品类应当被实例化。
首先定义一个接口
/**
* @author ieasy360_1
* 定义一个接口
*/
public interface Sender{
public void send();
}
创建类实现Sender接口
public class Qq implements Sender{
@Override
public void send() {
// TODO Auto-generated method stu
System.out.println("this is qq send!");
}
}
public class Weixin implements Sender {
@Override
public void send() {
// TODO Auto-generated method stub
System.out.println("this is Weixin send!");
}
}
创建一个工厂类
/**
* @author ieasy360_1
* 工厂类
*/
public class SenderFactory {
public Sender sendproduce(String type)
{
if(type.equals("qq"))
{
return new Qq();
}
else if(type.equals("wx"))
{
return new Weixin();
}
else
{
return null;
}
}
}
具体用法
/**
* @author ieasy360_1
*
*/
public class Test1 {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
SenderFactory factory = new SenderFactory();
Sender sender = factory.sendproduce("qq");
sender.send();
}
}
运行得到的结果
this is qq send!
原文:http://www.cnblogs.com/awkflf11/p/4370536.html