java 工厂模式

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;
}

}

工厂只负责选择实现, 实现类是具体的实现,接口是限定到底实现什么东西和返回什么东西

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值