Java程序开发讲究面向接口编程,隐藏具体的实现类,可是如何得到接口呢?
工厂类的命名规范:***Factory
单例工厂方法的命名规范:getInstance()
工厂、接口、实现类之间的技术边界:工厂只负责选择实现,实现类做正真的实现,而接口是限定到底实现什么东西和返回什么东西,三者之间分工明确
//接口
public interface DepApi {
public String t1();
}
实现1
public class Deplmpl1 implements DepApi{
@Override
public String t1() {
System.out.println("DepApi--Deplmpl1.t1()...");
return "Deplmpl1_t1()";
}
//下面这个方法在外面访问不到,因为被接口隔离了
public String t2() {
System.out.println("DepApi--Deplmpl1.t2()...");
return "Deplmpl1_t2()";
}
}
实现2
package cn.hncu.pattern.factory.dep;
public class Deplmpl2 implements DepApi{
@Override
public String t1() {
System.out.println("DepApi--Deplmpl2.t1()...");
return "Deplmpl2_t1()";
}
//下面这个方法在外面访问不到,因为被接口隔离了
public String t2() {
System.out.println("DepApi--Deplmpl2.t2()...");
return "Deplmpl2_t2()";
}
}
工厂类:
package cn.hncu.pattern.factory.dep;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
//工厂真正的作用是:选择实现
public class DepFactory {
// 工厂方法,命名规范:createDepApi,getDepApi,getDepInstance
public static DepApi getDepApi(){
Properties p = new Properties();
int type=1;
InputStream inStream;
try {
inStream = new FileInputStream("a.properties");
p.load(inStream);
type = Integer.parseInt(p.getProperty("type"));
} catch (IOException e) {
e.printStackTrace();
}
if(type==1){
return new Deplmpl1();
}
if(type==2){
return new Deplmpl2();
}
return null;
}
}
工厂只负责选择实现, 实现类是具体的实现,接口是限定到底实现什么东西和返回什么东西