工厂模式概念:
- 实例化对象,用工厂方式代替new操作
- 工厂模式包括工厂方法模式和抽象工厂模式
- 抽象工厂模式是工厂方法模式的扩展
我在慕课网上看了一个关于工厂模式的视频,感觉很不错,就把它记录下来了。我就直接上代码了。
1.目录结构
1.代码详解
HairInterface.java
package com.chen.project;
public interface HairInterface {
//实现了发型
public void draw();
}
定义头发接口类
LeftHair.java
package com.chen.project;
/**
* 画了一个左偏分发型
* @author chengming
*
*/
public class LeftHair implements HairInterface {
@Override
public void draw() {
System.out.println("左偏分发型");
}
}
画了一个左偏分的发型
RightHair.java
package com.chen.project;
public class RightHair implements HairInterface {
@Override
public void draw() {
System.out.println("右偏分发型");
}
}
画了一个右偏分发型
PropertiesReader.java,这是一个读取properties文件的类;将properties中的内容转换为map集合
package com.chen.project;
import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
public class PropertiesReader {
public Map<String, String> getProperties(){
Properties properties = new Properties();
Map<String, String> map = new HashMap<>();
InputStream inputStream = getClass().getResourceAsStream("type.properties");
try {
properties.load(inputStream);
Enumeration<?> ens = properties.propertyNames();
while(ens.hasMoreElements()){
String key = (String)ens.nextElement();
String value = properties.getProperty(key);
map.put(key, value);
}
} catch (IOException e) {
e.printStackTrace();
}
return map;
}
}
HairFactory.java,创建头发的工厂
package com.chen.project;
import java.util.Map;
/**
* 发型工厂
* @author chengming
*
*/
public class HairFactory {
public HairInterface getHair(String type){
if("left".equals(type)){
return new LeftHair();
}else if("right".equals(type)){
return new RightHair();
}else{
return null;
}
}
/**
* 根据className获取对象
* @param className
* @return
*/
public HairInterface getHairByClassName(String className){
try {
HairInterface hairInterface = (HairInterface) Class.forName(className).newInstance();
return hairInterface;
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
/**
* 根据key值到properties中找到对应的value,这个value就是类名全称
* @param key
* @return
*/
public HairInterface getHairByClassKey(String key){
try {
Map<String, String> map = new PropertiesReader().getProperties();
String className = map.get(key);
HairInterface hairInterface = (HairInterface) Class.forName(className).newInstance();
return hairInterface;
} catch (Exception e) {
}
return null;
}
}
HairTest.java,测试类
package com.chen.project;
public class HairTest {
public static void main(String[] args) {
HairFactory hairFactory = new HairFactory();
// HairInterface leftHair = hairFactory.getHairByClassName("com.chen.project.LeftHair");
// leftHair.draw();
HairInterface leftHair = hairFactory.getHairByClassKey("left");
leftHair.draw();
}
}
东西就这么多了,要想理解还得自己好好的敲打一遍