• 工厂设计模式


    定义:定义了一个创建对象的接口,但由子类决定要实例化的类是哪一个。工厂方法让类把实例化推迟到子类。

    举例说明:

    car接口:

    package factory;
    
    public interface Car {
    
        String getCarName();
    
    }

    car实例1:

    package factory;
    
    public class AudiCar implements Car {
    
        @Override
        public String getCarName() {
            return "audi";
        }
    
    }

    car实例2:

    package factory;
    
    public class BmwCar implements Car {
    
        @Override
        public String getCarName() {
            return "bmw";
        }
    
    }

    CarFactory抽象类:

    package factory;
    
    public abstract class CarFactory {
    
        Car car;
    
        public void saleCar() {
            car = createCar();
            System.out.println("create car");
            sale(car);
        }
    
        abstract Car createCar();
    
        void sale(Car car) {
            System.out.println("sale " + car.getCarName());
    
        }
    
    }

    具体工厂1:

    package factory;
    
    public class AudiFactory extends CarFactory {
    
        @Override
        Car createCar() {
            return new AudiCar();
        }
    
    }

    具体工厂2:

    package factory;
    
    public class BmwFacory extends CarFactory {
    
        @Override
        Car createCar() {
            return new BmwCar();
        }
    
    }

    测试类:

    package factory;
    
    public class Test {
    
        public static void main(String[] args) {
            CarFactory carFactory = new BmwFacory();
            carFactory.saleCar();
            System.out.println("**********");
            carFactory = new AudiFactory();
            carFactory.saleCar();
        }
    
    }

    执行结果:

    create car
    sale bmw
    **********
    create car
    sale audi
  • 相关阅读:
    SQL SEREVR IO
    INTEL
    windows performance
    The DiskSpd Storage Performance Tool
    machine Learning
    NOSQL
    X64 Deep Dive
    Debugging and performance,ETW
    Disk Performance
    WCF transport-and-message-security
  • 原文地址:https://www.cnblogs.com/silenceshining/p/12757632.html
Copyright © 2020-2023  润新知