1. 程式人生 > >JAVA 23種設計設計模式---工廠模式(工廠方法)

JAVA 23種設計設計模式---工廠模式(工廠方法)

設計模式中的工廠模式可大致分為3個,簡單工廠、工廠方法、抽象工廠。

今天整理的是工廠方法模式,介紹如下:

案列結構如下:

程式碼結構如下:

 

卡車:

package com.zxf.method;
//卡車(介面)
public interface Trunk_M {
    
    public void run();
}

卡車工廠:

package com.zxf.method;
//抽象工廠
public interface TrunkFactory {
    //建立卡車
    public Trunk_M produceTrunk();

}

奧迪卡車:

package com.zxf.method;

public class AodiTrunk implements Trunk_M {

    @Override
    public void run() {
        // TODO Auto-generated method stub
        System.out.println("奧迪卡車啟動!");

    }
}

奧迪卡車工廠:

package com.zxf.method;

public class AodiTrunkFactory implements TrunkFactory {

    @Override
    public Trunk_M produceTrunk() {
        // TODO Auto-generated method stub
        return new AodiTrunk();
    }
}

寶馬卡車:

public class BmwTrunk implements Trunk_M {

    @Override
    public void run() {
        // TODO Auto-generated method stub
        System.out.println("寶馬卡車啟動!");

    }
}

寶馬卡車工廠:

package com.zxf.method;

public class BmwTrunkFactory implements TrunkFactory {

    @Override
    public Trunk_M produceTrunk() {
        // TODO Auto-generated method stub
        return new BmwTrunk();
    }
}

顧客(測試類):

package com.zxf.method;

public class Cunstomer_M {
    public static void main(String[] args) {
        TrunkFactory bm = new BmwTrunkFactory();//多型的形式
        bm.produceTrunk().run();
        
        TrunkFactory ad = new AodiTrunkFactory();//多型的形式
        ad.produceTrunk().run();
    }
}

測試類: