java設計模式 之 抽象工廠模式

java設計模式 之 抽象工廠模式

抽象工廠模式:解決了工廠模式的弊端,當新加一個功能的時候,不會影響之前的代碼。

  • 接口 IMobile 代碼如下:

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package Factory;

/**
 *
 * @author dev
 */
public interface IMobile {
    public void printName();
}

  • 實現類 IPhoneMobile 代碼如下:

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package Factory;

/**
 *
 * @author dev
 */
public class IPhoneMobile implements IMobile {

    @Override
    public void printName() {
        System.out.println("我是一個iPhone手機!");
    }
    
}

  • 實現類 SamsungMobile 代碼如下:

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package Factory;

/**
 *
 * @author dev
 */
public class SamsungMobile implements IMobile {

    @Override
    public void printName() {
        System.out.println("我是一個三星手機!");
    }    
}

  • 接口 IFactory 代碼如下:

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package Factory;

/**
 *
 * @author dev
 */
public interface IFactory {
    public IMobile produce();
}

  • IPhone手機工場類 IPhoneFactory 代碼如下:

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package Factory;

/**
 *
 * @author dev
 */
public class IPhoneFactory implements IFactory {

    @Override
    public IMobile produce() {
        return new IPhoneMobile();
    }    
}

  • 三星手機工場類 SamsungFactory 代碼如下:

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package Factory;

/**
 *
 * @author dev
 */
public class SamsungMobile implements IMobile {

    @Override
    public void printName() {
        System.out.println("我是一個三星手機!");
    }    
}

  • 最後,main 函數如下:

public static void main(String[] args) {
        // TODO code application logic here
        IFactory factory = new IPhoneFactory();
        IMobile iphone = factory.produce();
        iphone.printName();
    }

  • 運行效果如下:


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章