Java设计模式——简单工厂设计模式

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("电视已正常工作");
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值