1.定义
由工厂类的对象决定创建哪种产品类的实例
2.目的
降低耦合
注:耦合是指使用者使用了一个具体的类,表示当前类依赖该具体的类,该具体的类改变,使用者将受到影响
3.解决办法
不使用具体的类,将具体的类进行抽象,自然而然,我们会联想到抽象类和接口,面向接口编程(面向抽象编程)
4.代码示例
a.思考下面的代码有何不足之处
public class SimpleFactory
{
public static void main(String[] args)
{
//耦合
//使用者使用了一个具体的类,具体的类改变使用者很容易受到影响
Phone phone = new Phone();
phone.working();
}
}
interface Work
{
public void working();
}
class Phone implements Work
{
public void working()
{
System.out.println("手机已正常工作");
}
}
class TV implements Work
{
public void working()
{
System.out.println("电视已正常工作");
}
}
很明显,上面的代码耦合性太强,使用者很容易因为产品类的改变而受到影响。这时,可以使用简单工厂设计模式降低耦合,由工厂类的对象决定创建哪种产品类的实例。
b.简单工厂设计模式弥补上述代码的不足之处
public class SimpleFactory
{
public static void main(String[] args)
{
//耦合被降低了
//由工厂类对象决定使用那种产品类的对象
Work work = new Factory("phone");
if(work != null)
{
work.working();
}
}
}
interface Work
{
public void working();
}
//工厂类
class Factory
{
public static Work getWork(String type)
{
if("phone".equals(type))
return new Phone();
if("tv".equals(type))
return new TV();
return null;
}
}
class Phone implements Work
{
public void working()
{
System.out.println("手机已正常工作");
}
}
class TV implements Work
{
public void working()
{
System.out.println("电视已正常工作");
}
}