jeudi 22 septembre 2016

Java architectural class design for a real world senario

This is the problem I need to implement it in java:

A Car can be a Petrol car or a Diesel Car, and a Hybrid Car is plugged with Petrol or Diesel but not both. Also, a hybrid car has the ability to run on electricity, while not using the petrol or diesel at all and it is decided at run time only whether to select electricity or the other fuel source (petrol or diesel as appropriate).

Here I need to implement with OOP concepts in mind for an example when the Hybrid car running in petrol mode method in the petrol type should be invoked as well as if its diesel the diesel class running method should be invoked.

I am very new to OOP and I came up with the following Design I know It's wrong if any one can help me please.

And I tried this with decorator design pattern just correct me if the deign is wrong for the above scenario..

Car Interface

public interface Car {
        public void running();
}

Petrol Car Class

class PetrolCar implements Car{

    public void running() {
        System.out.println("Running in Petrol");
    }

}

Diesel Car class

public class DieselCar implements Car{

    public void running() {
        System.out.println("Running in Diesel");
    }

}

Abstract Hybrid

public abstract class Hybrid implements Car{

    Car car;

    public Hybrid(Car car) {
        this.car=car;
    }

    public void running(){
        car.running();
    }

    abstract void hybridRunning();

}

Implementing Hybrid class

public class HybridCar extends Hybrid{

    public HybridCar(Car car) {
        super(car);
    }

    @Override
    void hybridRunning() {
        System.out.println("Running in Hybrid Mood");
    }

}

Testing as at run time user can select whether the car is hybrid petrol or hybrid diesel or petrol or diesel...

public class App {

    public static void main(String[] args) {
        String neededType = "Petrol";
        boolean hybrid = true;

        if (hybrid) {
            Hybrid hCar=null;
            if (neededType.equalsIgnoreCase("Petrol")) {
                hCar=(Hybrid)new HybridCar(new PetrolCar());    
            } else if (neededType.equalsIgnoreCase("Diesel")) {
                hCar=new HybridCar(new DieselCar());
            }
            hCar.hybridRunning();
            hCar.running();
        } else {
            Car car=null;
            if (neededType.equalsIgnoreCase("Petrol")) {
                car=new PetrolCar();
            } else if (neededType.equalsIgnoreCase("Diesel")) {
                car=new DieselCar();
            }

        }
    }
}

Is this Correct is there any short of issues regarding to OOP best practice Thanks in Advance

Aucun commentaire:

Enregistrer un commentaire