`
dengwenwei121
  • 浏览: 36148 次
  • 性别: Icon_minigender_1
  • 来自: 湖南
文章分类
社区版块
存档分类
最新评论

简单工厂模式

 
阅读更多

一、什么是简单工厂模式

简单工厂模式属于类的创建型模式,又叫做静态工厂方法模式。通过专门定义一个类来负责创建其他类的实例,被创建的实例通常都具有共同的父类。

二、模式中包含的角色及其职责

1.工厂(Creator)角色
简单工厂模式的核心,它负责实现创建所有实例的内部逻辑。工厂类可以被外界直接调用,创建所需的产品对象。

2.抽象(Product)角色
简单工厂模式所创建的所有对象的父类,它负责描述所有实例所共有的公共接口。

3.具体产品(Concrete Product)角色

简单工厂模式所创建的具体实例对象

package com.dw.test;

//2.抽象(Product)角色简单工厂模式所创建的所有对象的父类,它负责描述所有实例所共有的公共接口。
public interface Gather {
   void get();
}
package com.dw.test;

//3.具体产品(Concrete Product)角色简单工厂模式所创建的具体实例对象
public class apple implements Gather {
   //苹果的get方法
	public void get() {
		System.out.println("我是苹果");
	}
}

package com.dw.test;

/*1.工厂(Creator)角色简单工厂模式的核心,它负责实现创建所有实例的内部逻辑。
 * 工厂类可以被外界直接调用,创建所需的产品对象。
 * */
public class GatherFactory {
   //获取apple的实例
	public static Gather getApple() {
		return new apple();
	}
	//获取orange的实例
	public static Gather getOrange() {
		return new orange();
	}
	/**
	 * 获取所有产品对象
	 * @throws IllegalAccessException 
	 * @throws InstantiationException 
	 * @throws ClassNotFoundException 
	 */
	public static Gather getGather(String type) throws InstantiationException, IllegalAccessException, ClassNotFoundException
	{
		if(type.equalsIgnoreCase("apple"))
		{
		   return	apple.class.newInstance();
		}else if(type.equalsIgnoreCase("orange"))
		{
			return orange.class.newInstance();
		}
		else
		{
			System.out.println("找不到响应的实例化类");
			return null;
		}
	/*    //为达到通用
		Class<Gather>	gather=(Class<Gather>) Class.forName(type.trim());
	     return gather.newInstance();*/
	}
}

package com.dw.test;

public class MainClass {

	public static void main(String[] args) throws InstantiationException, IllegalAccessException, ClassNotFoundException {
      /*		apple apl=new apple();
		apl.get();
		orange org=new orange();
		org.get();*/
/*		Gather gather=new orange();
		Gather gather1=new apple();
		gather.get();
		gather1.get();*/
		//获得工厂类的实例
		/*Gather gather=GatherFactory.getApple();
		Gather gather1=GatherFactory.getOrange();
		gather.get();
		gather1.get();*/
		//Gather gather=GatherFactory.getGather("apple");
	   	Gather gather1=GatherFactory.getGather("orange");
		gather1.get();
		//gather1.get();
	}

}






分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics