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

设计模式:工厂模式

程序员文章站 2022-06-13 14:27:21
...

设计模式:工厂模式

 

设计模式:工厂模式

 

设计模式:工厂模式

 

代码示例:

定义一个Person接口

package com.test.simplefactory;

public interface Person {
	public String sayHello(String name);
	public String sayGoodbye(String name);
}

 

定义两个具体类,分别实现Person接口

package com.test.simplefactory;

public class Chinese implements Person {

	public String sayGoodbye(String name) {
		return "再见! "+name;
	}

	public String sayHello(String name) {
		return "你好! "+name;
	}

}

 

 

package com.test.simplefactory;

public class American implements Person {

	public String sayGoodbye(String name) {
		return "GoodBye! "+name;
	}

	public String sayHello(String name) {
		return "Hello! "+name;
	}

}

 

工厂类,根据参数生成具体实例

package com.test.simplefactory;

public class PersonFactory {
	public static Person getPerson(String name) {
		if (name.equals("chinese")) {
			return new Chinese();
		} else if (name.equals("american")) {
			return new American();
		} else {
			return null;
		}
	}
}

 

测试类

package com.test.simplefactory;

public class Client {
	public static void main(String[] args) {
		Chinese chinese = (Chinese) PersonFactory.getPerson("chinese");
		System.out.println(chinese.sayHello("lisi"));
		System.out.println(chinese.sayGoodbye("lisi"));
		
		American american = (American) PersonFactory.getPerson("american");
		System.out.println(american.sayHello("lisi"));
		System.out.println(american.sayGoodbye("lisi"));
	}
}