设计模式之工厂模式--简单工厂_JAVA_编程开发_程序员俱乐部

中国优秀的程序员网站程序员频道CXYCLUB技术地图
热搜:
更多>>
 
您所在的位置: 程序员俱乐部 > 编程开发 > JAVA > 设计模式之工厂模式--简单工厂

设计模式之工厂模式--简单工厂

 2013/12/12 16:09:12  Supanccy2013  程序员俱乐部  我要评论(0)
  • 摘要:packagecom.supan;publicinterfacePerson{publicvoidsay();}packagecom.supan;publicclassChineseimplementsPerson{publicvoidsay(){System.out.println("Iamchinese");}}packagecom.supan;publicclassAmericanimplementsPerson{publicvoidsay(){System.out.println
  • 标签:模式 设计 设计模式
class="java">package com.supan;
public interface Person {
	public void say();
}
package com.supan;
public class Chinese implements Person {
	public void say(){
		System.out.println("I am chinese");
	}
}
package com.supan;
public class American implements Person {
	public void say() {
		System.out.println("I am American;");
	}
}
package com.supan;
public interface Animal {
	public void eat();
}
package com.supan;
public class Dog implements Animal {
	public void eat() {
		System.out.println("dog is eatting");
	}
}
package com.supan;
public class Cat implements Animal {
	public void eat() {
		// TODO Auto-generated method stub
		System.out.println("Cat is eattting");
	}
}
//下面是重要的工厂类。
package com.supan;
public class PersonFactory {
	public Object getObject(String name){
		if(name.equals("Chinese")){
			return new Chinese();
		}else if(name.equals("American")){
		    return new American();	
		}else if(name.equals("dog")){
			return new Dog();
		}else if(name.equals("Cat")){
			return new Cat();
		}
		return null;
	}
}
//下面是测试类
package com.supan;
public class FactoryTest {
	public static void main(String[] args) {
		PersonFactory pf = new PersonFactory();
	     American a = (American)pf.getObject("American");
	     a.say();
	     Chinese chinese = (Chinese)pf.getObject("Chinese");
	     chinese.say();
	     Dog dog = (Dog)pf.getObject("dog");
	     dog.eat();
	     Cat cat = (Cat)pf.getObject("Cat");
	     cat.eat();
	}
}
发表评论
用户名: 匿名