设计模式之原型模式

0、原型模式(Prototype Pattern),嘿嘿,直接上代码吧

public abstract class Car implements Cloneable {
    abstract void go();

    protected String carName;

    @Override
    protected Object clone() {
        Object object = null;
        try {
            object = super.clone();
        } catch (CloneNotSupportedException e) {
            e.printStackTrace();
        }
        return object;
    }

    public String getCarName(){
        return carName;
    }
}
public class Audi extends Car {

    public Audi(String carName){
        this.carName = carName;
    }

    @Override
    void go() {
        System.out.println("奥迪发车了");
    }
}
public class BMW extends Car {

    public BMW(String carName){
        this.carName = carName;
    }

    @Override
    void go() {
        System.out.println("BMW发车啦");
    }
}
public class CarCache {
    private Map<String,Car> mCacheMap = new Hashtable();
    
    public Car getOneCar(String carName){
        if(carName == null || carName.isEmpty()) {
            throw new IllegalArgumentException("大哥,起码传参数传对吧");
        }
        Car tempCar = mCacheMap.get(carName);
        Car newCar = null;
        if(tempCar != null) {
            newCar = (Car)tempCar.clone();
        }
        return newCar;
    }

    public void loadCache(){
        Car audi = new Audi("A4L");
        Car bmw = new BMW("320Li");
        mCacheMap.put(audi.getCarName(),audi);
        mCacheMap.put(bmw.getCarName(),bmw);
    }
    
}
public class Main {
    public static void main(String args[]){
        CarCache cache = new CarCache();
        cache.loadCache();
        cache.getOneCar("A4L").go();
    }
}

对于原型模式,很有意思,把对象缓存在一个容器里,最后非要clone()一个,很有意思,做的好啊!

发布了711 篇原创文章 · 获赞 208 · 访问量 75万+
展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 精致技术 设计师: CSDN官方博客

分享到微信朋友圈

×

扫一扫,手机浏览