Java设计模式-简单工厂模式
简单工厂模式(逻辑判断)
对实现同一个接口的类,我们可以使用一个工厂类来封装这些类的创建,通过传入一个类的标识来获得该类的示例(逻辑判断)。这种设计模式我们称作简单工厂设计模式。
下面用UML图来表示该设计模式下类与类之间的关系
示例代码
package factory;
public class SimpleFactoryMethodTest
{
public static void main(String[] args)
{
SimpleFactory factory = new SimpleFactory();
Sender s1 = factory.createSender("email");
s1.send();
Sender s2 = factory.createeSender("sms");
s2.send();
}
}
class SimpleFactory
{
public Sender createSender(String name)
{
if ("email".equals(name))
{
return new EmailSender();
}
else if ("sms".equals(name))
{
return new SMSSender();
}
else
{
System.out.println(name + " not found!");
return null;
}
}
}
interface Sender
{
public void send();
}
class EmailSender implements Sender
{
@Override public void send()
{
System.out.println(getClass().getName() + " send");
}
}
class SMSSender implements Sender
{
@Override public void send()
{
System.out.println(getClass().getName() + " send");
}
}
简单工厂模式(多个方法)
多个方法的简单工厂模式本质上还是一种简单工厂模式,只不过将原来的逻辑判断分到了不同的执行方法中来,每一个不同的类对应一个产生它们的方法。这种模式可以避免出现逻辑判断条件不存在的错误,由工厂调用者选择实例化的类。
示例代码
package factory;
public class MultiFactoryMethodTest
{
public static void main(String[] args)
{
SimpleFactory factory = new SimpleFactory();
Sender s1 = factory.produceEmailSender();
s1.send();
Sender s2 = factory.produceSMSSender();
s2.send();
}
}
class SimpleFactory
{
public Sender produceEmailSender()
{
return new EmailSender();
}
public Sender produceSMSSender()
{
return new SMSSender();
}
}
interface Sender
{
public void send();
}
class EmailSender implements Sender
{
@Override public void send()
{
System.out.println(getClass().getName() + " send");
}
}
class SMSSender implements Sender
{
@Override public void send()
{
System.out.println(getClass().getName() + " send");
}
}
简单工厂模式(静态方法)
静态方法的简单工厂模式将原有工厂类中的方法改为静态方法,这样就不用创建工厂类实例了。
示例代码
package factory;
public class StaticFactoryMethodTest
{
public static void main(String[] args)
{
Sender s1 = SimpleFactory.produceEmailSender();
s1.send();
Sender s2 = SimpleFactory.produceSMSSender();
s2.send();
}
}
class SimpleFactory
{
public static Sender produceEmailSender()
{
return new EmailSender();
}
public static Sender produceSMSSender()
{
return new SMSSender();
}
}
interface Sender
{
public void send();
}
class EmailSender implements Sender
{
@Override public void send()
{
System.out.println(getClass().getName() + " send");
}
}
class SMSSender implements Sender
{
@Override public void send()
{
System.out.println(getClass().getName() + " send");
}
}