設計模式之原廠模式

來源:互聯網
上載者:User

標籤:

設計模式之原廠模式

  原廠模式專門負責將有大量的共同的介面的類執行個體化。工程模式可以決定哪一個類執行個體化,不必事Crowdsourced Security Testing道每次要執行個體化哪一個類。

  原廠模式有三種形態:
  1)簡單原廠模式(Simple Factory):又稱靜態Factory 方法模式
  2)Factory 方法模式(Factory Method):又稱為多型原廠模式
  3)抽象原廠模式(Abstract Factory):又稱為工具箱模式

  PS:簡單原廠模式和Factory 方法模式可以統稱為普通原廠模式

 

例:養動物為例
public interface Animal {    void sound();}public class Cat implements Animal{    @Override    public void sound() {        System.out.println("喵喵。。。");    }}public class Dog implements Animal {    @Override    public void sound() {        System.out.println("WangWang。。。");    }}

 

簡單原廠模式
public class SimpleAnimalFactory {    public static Animal keep(String arg) {        Animal animal = null;        switch(arg) {        case "cat":            animal = new Cat();            break;        case "dog":            animal = new Dog();            break;        }        return animal;    }}
Factory 方法模式
public interface AnimalFactory {    Animal keep();}public class CatFactory implements AnimalFactory {    @Override    public Animal keep() {        return new Cat();    }}public class DogFactory implements AnimalFactory {    @Override    public Animal keep() {        return new Dog();    }}

可以看出,每增加一種Animal就需要增加該類的工廠,當Animal種類越來越多時就會造成工廠泛濫。

 

除了養小動物我們有時還會養一些花
public interface Flower {    void color();}public class Rose implements Flower {    @Override    public void color() {        System.out.println("紅玫瑰");    }}public class Lily implements Flower {    @Override    public void color() {        System.out.println("白百合");    }}

 

抽象工廠
public abstract class AbstractFactory {    abstract Animal keep();    abstract Flower grow();}public class DefaultFactory extends AbstractFactory {    @Override    Animal keep() {        return new Dog();    }    @Override    Flower grow() {        return new Rose();    }}

 

測試

public class Test {    public static void main(String[] args) {        Animal a1 = SimpleAnimalFactory.keep("dog");        a1.sound();                AnimalFactory af = new CatFactory();        Animal a2 = af.keep();        a2.sound();                AbstractFactory factory = new DefaultFactory();        Animal animal = factory.keep();        animal.sound();        Flower flower = factory.grow();        flower.color();    }}

設計模式之原廠模式

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.