简单的工厂模式
简单的工厂模式(SimpleFactory Pattern):简单工厂模式又称静态工厂方法(Static Factory Method)模式,它属于类创建模式,它不属于GoF提出的23中设计模式中。简单的工厂模式通过参数获取不同类的实例对象。AbstractXXX可以是一个抽象类或者是一个接口。
Java代码如下:
//Perosn.java
package com.designpattern.simplefactory;
public interface Person {
public void say();
}
//Man.java
package com.designpattern.simplefactory;
public class Man implements Person {
public void say() {
System.out.println("I'am a man!!!");
}
}
//Woman,java
package com.designpattern.simplefactory;
public class Woman implements Person {
public void say() {
System.out.println("I'am a woman!!!");
}
}
//NvwaFactory.java
package com.designpattern.simplefactory;
public class NvwaFactory {
public static Person madePerson(String type) throws Exception{
if(type.equalsIgnoreCase("man")){
return new Man();
}else if(type.equalsIgnoreCase("woman")){
return new Woman();
}else{
System.out.println("sorry,Nvwa can't made "+type);
throw new Exception("sorry,Nvwa can't made "+type);
}
}
}
//test.java
package com.designpattern.simplefactory;
public class test {
public static void main(String [] args){
try {
Person p1 =NvwaFactory.madePerson("man");
p1.say();
Person p2 = NvwaFactory.madePerson("woman");
p2.say();
Person p3 = NvwaFactory.madePerson("robot");
p3.say();
} catch (Exception e) {
e.getMessage();
e.printStackTrace();
}
}
}