A Collection of an Abstract Class (or something like that…)

后端 未结 4 1586
[愿得一人]
[愿得一人] 2021-01-05 04:29

The Scenario

I\'m making a program in Java that involves cars.

NOTE: I\'ve simplified this scenario (to the best of my ability) to make

4条回答
  •  没有蜡笔的小新
    2021-01-05 05:02

    I used the method described in Daryl Teo's answer, but I modified it a little bit to include an enum (since there are a finite number of individual cars). Because his answer was so instrumental to the development of my final solution, I selected it as the best answer.

    The CarCreationStrategy interface:

    public interface CarCreationStrategy {
        public void buildCar(Car car);
    }
    
    enum CarTypes implements CarCreationStrategy{
        CORVETTE() {
            @Override
            public String toString() {
                return "Corvette";
            }
    
            public void buildCar(Car car) {
                car.setSpeed (0.9);
            }
        },
        CLUNKER() {
            @Override
            public String toString() {
                return "A piece of junk!";
            }
    
            public void buildCar(Car car) {
                car.setSpeed (0.1);
            }
        }
    }
    

    The Cars class:

    public class Cars {
        private List cars = new List;
    
        public void createCar() {
            // There would be logic here to determine what kind
            // We'll make a Corvette just to demonstrate
            Car car = new Car(1998, CarTypes.CORVETTE);
            cars.add(car);
        }
    }
    

    The Car class:

    public class Car {
        private int year;
        private double speed;
    
        public Car(int year, CarType type) {
            this.year = year;
            type.buildCar(this);  // Sets the speed based on CarType
        }
    
        public void setSpeed(double speed) {
            this.speed = speed;
        }
    }
    

提交回复
热议问题