Java 设计模式 之 工厂模式 Factory

http://www.verejava.com/?id=16998975541155

package com.factory.theory;

public class TestFactory
{
	public static void main(String[] args)
	{
		Product p=Factory.create(0);
		System.out.println(p.getName());
		p=Factory.create(1);
		System.out.println(p.getName());
	}
}





package com.factory.theory;

public class Factory
{
	public static Product create(int type)
	{
		Product p=null;
		if(type==0)//如果类型为 0 创建产品 A
		{
			p=new ProductA();
		}else if(type==1) //如果类型为 1 创建产品 B
		{
			p=new ProductB();
		}
		return p;
	}

}





package com.factory.theory;

public interface Product
{
	public String getName();
}





package com.factory.theory;

public class ProductA implements Product
{

	@Override
	public String getName()
	{
		return "产品 A";
	}

}





package com.factory.theory;

public class ProductB implements Product
{

	@Override
	public String getName()
	{
		return "产品 B";
	}

}


http://www.verejava.com/?id=16998975541155

posted @ 2018-06-28 09:09  verejava  阅读(86)  评论(0编辑  收藏  举报