JAVA花園佈局(抽象工廠模式)

實現抽象工廠模式的技術要點如下:

· 抽象工廠模式和工廠方法模式的區別就在於需要創建對象的複雜程度上。而且抽象工廠模式是這三種模式中最爲抽象、最具一般性的。

· 使用抽象工廠模式需要滿足以下條件:系統中有多個產品族,而系統一次只可能消費其中一族產品;同屬於同一個產品族的產品。

· 抽象工廠模式的組成部分與工廠方法模式的組成部分相同

 package JAVA_Project_01_05;

/*
實現抽象工廠模式的技術要點如下:

· 抽象工廠模式和工廠方法模式的區別就在於需要創建對象的複雜程度上。而且抽象工廠模式是這三種模式中最爲抽象、最具一般性的。

· 使用抽象工廠模式需要滿足以下條件:系統中有多個產品族,而系統一次只可能消費其中一族產品;同屬於同一個產品族的產品。

· 抽象工廠模式的組成部分與工廠方法模式的組成部分相同
 */

class Plant {//植物

        String name;//植物名稱

        public Plant(String name) {//帶參數的構造方法

                this.name = name;

        }

        public String getName() {

                return name;

        }

        public void setName(String name) {

                this.name = name;

        }

}

abstract class Garden {//花園類

        public abstract Plant getShade();//花臺上的植物

        public abstract Plant getCenter();//中間的植物

        public abstract Plant getBorder();//邊上的植物

}

class Elegant extends Garden {//典雅型

        public Plant getBorder() {

                return new Plant("蘭草");

        }

        public Plant getCenter() {

                return new Plant("榕樹");

        }

        public Plant getShade() {

                return new Plant("鬱金香");

        }

}

class Practical extends Garden//實用型

{

        public Plant getShade() {

                return new Plant("葡萄");

        }

        public Plant getCenter() {

                return new Plant("石榴");

        }

        public Plant getBorder() {

                return new Plant("絲瓜");

        }

}
class Lazy extends Garden//懶人型

{

        public Plant getShade() {

                return new Plant("月季");

        }

        public Plant getCenter() {

                return new Plant("茶花");

        }

        public Plant getBorder() {

                return new Plant("竹");

        }

}

class GardenMaker {//抽象工廠類

        private static Garden garden;

        public static Garden getGarden(String type) {

                garden = new Elegant();//默認情況

                if (type.equals("實用型"))

                        garden = new Practical();

                if (type.equals("懶人型"))

                        garden = new Lazy();

                return garden;

        }

}

public class TextAbstractFactory {//操作抽象工廠模式的類

        public static void main(String[] args) {//Java程序主入口處

                Garden garden = GardenMaker.getGarden("實用型");//傳入參數調用方法獲得實例

                Plant shade = garden.getShade();//獲取花園植物

                Plant center = garden.getCenter();

                Plant border = garden.getBorder();

                System.out.println("花臺上的植物:" + shade.getName());

                System.out.println("中間的植物:" + center.getName());

                System.out.println("邊上的植物:" + border.getName());

        }

}

/*
(1)程序中定義一個植物類、一個花園的抽象類、三個不同花園的抽象類的實現類以及一個抽象工廠類。程序中使用抽象工廠類實現對不同花園的選擇。
使用這樣模式能夠將實現類和它們的生成過程完全分割開來。實現類被隱藏在工廠類中,調用者不必知道實現類的任何信息。
(2)雖然抽象工廠中的子類繼承了同一個超類,但是它們也可以擁有與其他子類不同的方法。
 */


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