工廠模式
簡(jiǎn)單工廠模式
工廠模式是一種架構(gòu)設(shè)計(jì)模式瞬欧,符合代碼的設(shè)計(jì)原則僧凰,開閉原則(只對(duì)擴(kuò)展開放,對(duì)修改關(guān)閉)和單一職責(zé)原則 继效,用戶只需要調(diào)用Pay 接口症杏,符合依賴倒置原則,以支付為例瑞信,在開發(fā)過程中厉颤,可能需要接入各種各樣的支付方式,可以使用簡(jiǎn)單工廠模式進(jìn)行管理凡简,當(dāng)需要添加新的支付方式時(shí)逼友,只需要新建一個(gè)類精肃,實(shí)現(xiàn)Pay 接口,然后再PayFactory中添加初始化帜乞。
public interface Pay{
void pay();
}
...
public class AliPay implements Pay {
@Override
public void pay() {
System.out.println("a li pay");
}
}
...
public class QQPay implements Pay {
@Override
public void pay() {
System.out.println("qq pay");
}
}
...
public class WeChatPay implements Pay {
@Override
public void pay() {
System.out.println("wei chat pay");
}
}
...
//支付的工廠類司抱,類型具體的支付實(shí)例
public class PayFactory {
private static volatile PayFactory mInstance;
private PayFactory() {
}
public static PayFactory getInstance() {
if (mInstance == null) {
synchronized (PayFactory.class) {
if (mInstance == null) {
mInstance = new PayFactory();
}
}
}
return mInstance;
}
public Pay getPayInstence(Pay.PAY_TYPE type) {
Pay pay = null;
if (type == Pay.PAY_TYPE.ALI_PAY) {
pay = new QQPay();
} else if (type == Pay.PAY_TYPE.QQ_PAY) {
pay = new QQPay();
} else if (type == Pay.PAY_TYPE.WEICHAT_PAY) {
pay = new WeChatPay();
}
return pay;
}
}
...
public static void main(String[] args){
Pay payInstance = PayFactory.getInstance().getPayInstence(Pay.PAY_TYPE.QQ_PAY);
payInstance.pay();
}