工厂方法

工厂方法代码示例


public class FactoryMethod {

    public static void main(String[] args) {
        TransportFactory factory = new TransportFactory();
        Movable movable = factory.createTransport();
        movable.move();
    }
}

class TransportFactory {
    Movable createTransport() {
        // do something...
        System.out.println("TransportFactory.createTransport");
        return new Car();
    }
}

interface Movable {
    void move();
}

class Car implements Movable {

    @Override
    public void move() {
        System.out.println("Car.move");
    }
}

class Train implements Movable {

    @Override
    public void move() {
        System.out.println("Train.move");
    }
}
posted @ 2023-05-08 15:05  我见青山应如是  阅读(3)  评论(0编辑  收藏  举报