簡單原廠模式(SimpleFactory)__java編程

來源:互聯網
上載者:User

一.定義

從設計模式的類型上來說,簡單原廠模式是屬於建立型模式,又叫做靜態Factory 方法(Static Factory Method)模式,但不屬於23種GOF設計模式之一。簡單原廠模式是由一個工廠對象決定建立出哪一種產品類的執行個體。簡單原廠模式是原廠模式家族中最簡單實用的模式,可以理解為是不同原廠模式的一個特殊實現。

二.實現

/**
 * 1、定義一個介面 ----抽象產品
 * 2、定義實現該介面的類 ----具體產品
 * 3、定義一個類將具體產品統一管理,用來對具體產品建立對象做準備----工廠
 *     
 *       抽象產品(介面)
 *                  ↓           
 *     具體產品(類)  ←    工廠(靜態方法) 
 *     
 */

抽象介面Fruit public interface Fruit {
public void plant();
public void grow();
public void harvest();

}

具體產品類

public class Apple implements Fruit{
@Override
public void plant() {
System.out.println("種植蘋果");
}


@Override
public void grow() {
System.out.println("蘋果生長");
}


@Override
public void harvest() {
System.out.println("收穫蘋果");
}

public class Grape implements Fruit {
private boolean seedless;
public boolean isSeedless() {
return seedless;
}
public void setSeedless(boolean seedless) {
this.seedless = seedless;
}
@Override
public void plant() {
System.out.println("種植葡萄");
}
@Override
public void grow() {
System.out.println("葡萄生長");
}
@Override
public void harvest() {
System.out.println("收穫葡萄");
}
}

public class StrawBerry implements Fruit {
@Override
public void plant() {
System.out.println("種植草莓");
}
@Override
public void grow() {
System.out.println("草莓生長");
}
@Override
public void harvest() {
System.out.println("收穫草莓");
}
}

工廠 

public class FruitGardner {
/**
* 靜態Factory 方法
*/
public static Fruit factory(String which) throws Exception {
if(which.equalsIgnoreCase("apple")){
return new Apple();
}else if(which.equalsIgnoreCase("grape")){
return new Grape();
}else if(which.equalsIgnoreCase("strawberry")){
return new StrawBerry();
}else {
throw new Exception("水果輸入錯誤");
}
}
}







聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.