工厂模式
工厂模式:即通过一个类进行创建同一类型的不同对象。
?
例:有一个接口《InterfaceOne》、两个类《CalssOne》《ClassTwo》,具体代码如下:
package com.mkf.pattern;public interface InterfaceOne {public String sayHello(String name);}package com.mkf.pattern.impl;import com.mkf.pattern.InterfaceOne;public class CalssOne implements InterfaceOne {public CalssOne() {System.out.println("CalssOne 被创建");}@Overridepublic String sayHello(String name) {return "CalssOne Say: Hello " + name;}}package com.mkf.pattern.impl;import com.mkf.pattern.InterfaceOne;public class ClassTwo implements InterfaceOne {public ClassTwo(){System.out.println("ClassTwo 被创建");}@Overridepublic String sayHello(String name) {return "ClassTwo Say: Hello " + name;}}
?
?
我们用一个类进行创建《CalssOne》《ClassTwo》对象,
具体的工厂类如下:
?
package com.mkf.pattern;import com.mkf.pattern.impl.CalssOne;import com.mkf.pattern.impl.ClassTwo;public class FactoryPattern {public static InterfaceOne createObject(Class<? extends InterfaceOne> class1){InterfaceOne io = null;try {io = class1.newInstance();} catch (InstantiationException e) {e.printStackTrace();} catch (IllegalAccessException e) {e.printStackTrace();}return io;}public static void main(String[] args) {System.out.println(FactoryPattern.createObject(CalssOne.class).sayHello("CalssOne"));System.out.println(FactoryPattern.createObject(ClassTwo.class).sayHello("ClassTwo"));}}
?