簡體   English   中英

如何創建抽象工廠以實例化 java 中的對象

[英]how to create abstract factory to instantiate objects in java

我想創建一個抽象工廠。 這是我嘗試過的。

//抽象 class 工人

public abstract class Worker {
    String phoneNumber;
    String firstName;
    String lastName;
    String workerType;
    String ifu;
    String imageParth;
    //....
  public String getWorkerType() {
        return workerType;
    }
}

// 擴展工人的電工 class

package worker.domain.worker;

public class Electrician extends Worker{
    
    
    public Electrician() {}
    public Electrician(String phoneNumber, String firstName, String lastName, String ifu, String workerType,
            String imageParth) {
        super(phoneNumber, firstName, lastName, ifu,workerType, imageParth);
    }
    
    
    public String getWorkerType() {
        return "Electrician";
    }
    
}

//梅森class

package worker.domaine.worker;

public class Mason extends Worker{
    
    public Mason() {};

    public Mason(String phoneNumber, String firstName, String lastName, String ifu,String workerType,
            String imageParth) {
        super(phoneNumber, firstName, lastName, ifu, workerType, imageParth);
    }
    
    String getworkerType() {
        return "Mason";
    }
}

// 接口 WorkerAbstractFactory

package worker.domaine.worker;

public interface WorkerAbstractFactory {
    Worker createWorker(String typeWorker);
}

//

public class WorkerFactory implements WorkerAbstractFactory{

    @Override
    public Worker createWorker(String typeWorker) {
        Worker worker = null;
        if(worker != null) {
            switch (typeWorker) {
            case "Electrician":
                Electrician electrician =new Electrician();
                electrician = new Electrician (electrician.getPhoneNumber(), electrician.getFirstName(), electrician.getLastName(), electrician.getIfu(), electrician.getWorkerType(),electrician.getImageParth());
                
            case "Mason":
                Mason mason =new Mason();
                mason = new Mason (mason.getPhoneNumber(), mason.getFirstName(), mason.getLastName(), mason.getIfu(), mason.getworkerType(),mason.getImageParth());
                }}

//應用程序 class

public class WorkerFactoryProvider {
    
     public static WorkerAbstractFactory getWorkerFactory(String workerCategory) {
         //WorkerFactory workerFactory = new WorkerFactory();
         WorkerFactory workerFactory = new WorkerFactory();
         if (workerCategory != null) {
             switch (workerCategory) {
                case "Electrician":
                    Worker worker1 = workerFactory.createWorker("Electrician");
                    worker1.getWorkerType();
                    String a=worker1.getWorkerType();
                    System.out.println(a);  
                    
                case "Mason":
                    Worker worker2 = workerFactory.createWorker("Mason");
                    worker2.getWorkerType();
                    String b=worker2.getWorkerType();
                    System.out.println(b);               
             
             }
             
             
         }
         return null;
     }

你認為它可以這樣工作嗎? 現在,如果我真的想要一個具體的 object,怎么辦? 因為我想寫一個方法來根據類型計算每個工人的工資,例如我如何在方法中使用我的抽象工廠來返回每種類型。

您有一個 Worker 類型的 class 層次結構。 要實例化那些你可以只使用一個獨立的工廠 class,你不需要一個抽象工廠。 例如,這就足夠了:

public class WorkerFactory {            
    public Worker createWorker(String workerType) {
        switch (workerType) {
            case "Electrician": return new Electrician();                    
            case "Mason": return new Mason();
        }
    }
}

抽象工廠模式更加精細,允許為相關的對象層次結構注入不同的具體工廠,因此客戶端不需要知道差異。 例如,您可以有一個抽象的 TransportationFactory:

interface Transportation {
    void travelTo(String destination);
}

interface TransportationFactory {
    Transportation simple();
    Transportation luxurious();
}

以及兩個具體的實現(匹配兩個不同但相似的 class 層次結構):

class WaterTransporationFactory {
   Transportation simple() {
       return new Kayak();
   }
   Transportation luxurious() {
       return new Yacht();
   }
}

和:

class LandTransporationFactory {
   Transportation simple() {
       return new Bike();
   }
   Transportation luxurious() {
       return new RaceCar();
   }
}

這種模式的好處是客戶端可以配置為使用水路或陸路運輸(或稍后添加的新航空運輸),而無需進行任何更改:

class Client {

    private TransportationFactory transportationFactory;

    public Client(TransportationFactory transportationFactory) {
        this.transportationFactory = transportationFactory;
    }

    public void travel(String destination) {
        transporationFactory.simple().travelTo(destination);
    }

    public void travelInStyle(String destination) {
        transporationFactory.luxurious().travelTo(destination);
    }

}

編輯:您可以更改簡單/豪華的方法以匹配您的示例風格。 我也更喜歡避免條件邏輯,讓創建的類自己確定它們的可用性。 這進一步解耦,允許以最少的代碼更改添加層次結構成員:

interface Transportation {
    void travelTo(String destination);
    // extra method to allow the class to specify its own type
    TransporationType getType();
}

// intermediate interface to distinguish Water from Land
interface WaterTransporation extends Transportation {
}

class Kayak implements WaterTransportation {

    void travelTo(String destination) {
        // splash splash
    }

    TransporationType getType() {
        return TransporationType.SIMPLE;
    }
}

class WaterTransporationFactory {

   private WaterTransportation[] waterTransporations;

   // Inject all available beans implementing WaterTransporation
   // e.g. using Spring or some other dependency injection mechanism
   public WaterTransporationFactory( WaterTransportation[] waterTransporations) {
       this.waterTransporations = waterTransporations;
   }

   public Transportation create(TransporationType type) {
       for(WaterTransportation waterTransportation : waterTransporations) { 
           if (waterTransportation.getType() == type) {
               return waterTransportation;
           }
       }
       throw new IllegalArgumentException("No implementation for WaterTransportation type=" + type);
   }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM