设计模式:工厂模式
程序员文章站
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"));
}
}
上一篇: 水浒传中最有趣的绰号,让人苦笑不得
下一篇: xampp访问数据库出错!