工厂方法模式&&抽象工厂模式

1.工厂方法模式

public interface Car {
    void run();
}

public class BydCar implements Car{
    @Override
    public void run() {
        System.out.println("我是比亚迪汽车");
    }
}

public class AudoCar implements Car {
    @Override
    public void run() {
        System.out.println("我是奥迪汽车");
    }
}

public interface CarFactory {
    Car createCar();
}

public class BydFactory implements CarFactory {
    @Override
    public Car createCar() {
        return new BydCar();
    }
}

public class AudoFactory implements CarFactory {
    @Override
    public Car createCar() {
        return new AudoCar();
    }
}

public class Client {
    public static void main(String[] args) {
        CarFactory factory1=new BydFactory();
        CarFactory factory2=new AudoFactory();
        Car car1 = factory1.createCar();
        Car car2 = factory2.createCar();
        car1.run();
        car2.run();
    }
}

2.抽象工厂模式

public interface CarFactory{
    Seat createSeat();
    Tyre createTyre();
}
class HighFactory implements CarFactory{
    @Override
    public Seat createSeat() {
        return new HighSeat();
    }

    @Override
    public Tyre createTyre() {
        return new HighTyre();
    }
}
class LowFactory implements CarFactory{
    @Override
    public Seat createSeat() {
        return new LowSeat();
    }

    @Override
    public Tyre createTyre() {
        return new LowTyre();
    }
}
interface Seat{
    void sit();
}
interface Tyre{
    void run();
}
class HighSeat implements Seat{
    @Override
    public void sit() {
        System.out.println("高级座椅");
    }
}
class LowSeat implements Seat{
    @Override
    public void sit() {
        System.out.println("低级座椅");
    }
}
class HighTyre implements Tyre{
    @Override
    public void run() {
        System.out.println("高级轮胎");
    }
}
class LowTyre implements Tyre{
    @Override
    public void run() {
        System.out.println("低级轮胎");
    }
}


public class Client {
    public static void main(String[] args) {
        CarFactory factory=new HighFactory();
        Seat seat1 = factory.createSeat();
        seat1.sit();
        CarFactory factory2=new LowFactory();
        Seat seat2 = factory2.createSeat();
        seat2.sit();
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值