2016-7-5 Design Patterns : Facade

问题:

class ComputerShop {
    public boolean isHaveCPU = true;
    public boolean isHaveHardDisk = true;
    public boolean isHaveMemory = true;
}

class Customer {
    private static Customer customer = null;
    private static ComputerShop shop = null;

    public static Customer getCustomer() {
        if (customer == null) {
            customer = new Customer();
            shop = new ComputerShop();
        }

        return customer;
    }

    public ComputerShop getComputerShop() {
        return shop;
    }
}

class GetCPU {
    public void buy() {
        ComputerShop shop = Customer.getCustomer().getComputerShop();
        if (shop.isHaveCPU) {
            System.out.println("buy cpu");
        }
    }
}

class GetHardDisk {
    public void buy() {
        ComputerShop shop = Customer.getCustomer().getComputerShop();
        if (shop.isHaveHardDisk) {
            System.out.println("buy harddisk");
        }
    }
}

class GetMemory {
    public void buy() {
        ComputerShop shop = Customer.getCustomer().getComputerShop();
        if (shop.isHaveMemory) {
            System.out.println("buy memory");
        }
    }
}

public class Problem {
    public static void main(String[] args) {

        new GetCPU().buy();
        new GetHardDisk().buy();
        new GetMemory().buy();
    }
}

有何问题:

get各个零件需要与customer内部的模块进行多次交互

一旦computershop中出现品种变化(CPU下架了),那么main(调用)中getcpu也要进行修改了

解决:

class Facade {
    public void onestop() {
        new GetCPU().buy();
        new GetHardDisk().buy();
        new GetMemory().buy();
    }
}

public class Resolve {
    public static void main(String[] args) {
        new Facade().onestop();
    }
}

增加一个Facade类即可.

 

posted on 2016-07-05 16:31  背靠背  阅读(103)  评论(0编辑  收藏  举报

导航