欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

设计模式:简单工厂 javapatternsimplefactory 

程序员文章站 2022-07-15 09:21:21
...
简单工厂就是把if-else语句放到了Factory中,代码如下:
package com.zsk.pattern.simpleFactory;

public interface Mobile {
	
	public void prepare();
	public void box();
	public void sell();
}
package com.zsk.pattern.simpleFactory;

public class GSM implements Mobile {

	@Override
	public void prepare() {
		System.out.println("prepare GSM phone");

	}

	@Override
	public void box() {
		System.out.println("box  GSM phone");

	}

	@Override
	public void sell() {
		System.out.println("sell GSM phone");
	}
	

}
package com.zsk.pattern.simpleFactory;

public class CDMA implements Mobile {

	@Override
	public void prepare() {
		System.out.println("prepare CDMA phone");

	}

	@Override
	public void box() {
		System.out.println("box  CDMA phone");

	}

	@Override
	public void sell() {
		System.out.println("sell  CDMA phone");
	}
	

}
package com.zsk.pattern.simpleFactory;

public class MobileFactory {

	public Mobile CreateMobile(String kind)
	{
		if("CDMA".equals(kind))
		{
			return new CDMA();
		}
		else if("GSM".equals(kind))
		{
			return new GSM();
		}
		else
		{
			return null;			
		}
		
	}
}
package com.zsk.pattern.simpleFactory;

public class TestSimpleFactory {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		MobileFactory mobileFactory = new MobileFactory();
		Mobile mobile = mobileFactory.CreateMobile("CDMA");
		mobile.prepare();
		mobile.box();
		mobile.sell();

	}
}