常用设计模式

单例模式

1.单例模式算是非常常用的一种设计模式
1.1懒汉式

public class Lazzy {
    private Lazzy(){
        System.out.println(Thread.currentThread().getName()+"ok");
    }
    private volatile static Lazzy lazzy=null;
    //普通模式
//    public static Lazzy getInstance(){
//        if (lazzy==null){
//            lazzy=new Lazzy();
//        }
//        return lazzy;
//    }

    //双重检测锁模式 懒汉单例 DCL懒汉式
    public static Lazzy getInstance(){
        if (lazzy==null){
            synchronized (Lazzy.class){
                if (lazzy==null){
                    lazzy=new Lazzy();//不是原子性操作
                }
            }
        }
        return lazzy;
    }
}

1.2 饿汉式

public class Hungey {
    //构造器私有化
    //单例模式能够保证一个类仅有唯一的实例,并提供一个全局访问点。多用于计数
    //单例模式主要有3个特点:
    //1、单例类确保自己只有一个实例。
    //2、单例类必须自己创建自己的实例。
    //3、单例类必须为其他对象提供唯一的实例。
  private Hungey(){}
  private static final Hungey hungry=new Hungey();
  public static Hungey getInstance(){
      return hungry;
  }
}

工厂模式

用买车子来举个例子,无论有多少个品牌,我们买车都只用找汽车厂,在增加汽车品牌时,也不用去改动别的代码。
1.1 简单工厂模式

总的类

Aodi

public class Aodi implements Car{
    @Override
    public void name() {
        System.out.println("奥迪汽车");
    }
}

接口Car

public interface Car {
    void name();
}

Jiebao

public class Jiebao implements Car{

    @Override
    public void name() {
        System.out.println("捷豹汽车");
    }
}

CarFactory

public class CarFactory {
    public static Car getAodi(){
        return new Aodi();
    }
    public static Car getJiebao(){
        return new Jiebao();
    }
}

Consumer

public class Consumer {
    public static void main(String[] args) {
        //  W一:
//        Car car1=new Aodi();
//        Car car2=new Jiebao();
//        car1.name();
//        car2.name();
        //W二:
        Car car1=CarFactory.getAodi();
        Car car2=CarFactory.getJiebao();
    }

1.2工厂方法模式
和简单工厂不同的是,每个汽车都有自己的工厂,每个工厂都要实现工厂的接口,买什么车就找到什么工厂。
在这里插入图片描述
接口 Car

public interface Car {
    void name();
}

接口CarFactory

public interface CarFactory {
     Car getCar();
}

Aodi

ublic class Aodi implements Car {
    @Override
    public void name() {
        System.out.println("奥迪汽车");
    }
}

AodiFactory

public class AodiFactory implements CarFactory{
    @Override
    public Car getCar() {
        return new Aodi();
    }
}

Jiebao

public class Jiebao implements Car {

    @Override
    public void name() {
        System.out.println("捷豹汽车");
    }
}

JiebaoFactory

public class JiebaoFactory implements CarFactory{

    @Override
    public Car getCar() {
        return new Jiebao();
    }
}

要增加一个新的品牌也很简单,直接增加之后,实现接口就可以
Mobai

public class Mobai implements Car{

    @Override
    public void name() {
        System.out.println("膜拜自行车");
    }
}

MobaiFactory

ublic class MobaiFactory implements CarFactory {
    @Override
    public Car getCar() {
        return new Mobai();
    }
}

Consumer

public class Consumer {
    public static void main(String[] args) {
        Car car1 = new AodiFactory().getCar();
        Car car2 = new JiebaoFactory().getCar();
        car1.name();
        car2.name();

        Car car3 = new MobaiFactory().getCar();
        car3.name();

    }

}

1.3 抽象工厂模式

抽象工厂,简单来说就是工厂中的工厂,一个东西被分为两个组,用华为手机来举例,它既可以说是手机这个族,同时又是华为这个品牌,这里用华为和小米产品来举例。
在这里插入图片描述
PhoneProduct接口

public interface PhoneProduct {
    void start();
    void close();
    void call();
}

ProductFactory接口

ublic interface ProductFactory {
    //生产手机
    PhoneProduct phoneProduct();
    //生成路由器
    RouteProduct routeProduct();
}
`

``
RouteProduct接口

public interface RouteProduct {
void start();
void close();
void connectwifi();
}

HuaweiFactory

public class HuaweiFactory implements ProductFactory {
@Override
public PhoneProduct phoneProduct() {
return new HuaweiPhone();
}

@Override
public RouteProduct routeProduct() {
    return new HuaweiRoute();
}

}

HuaweiPhone

public class HuaweiPhone implements PhoneProduct {
@Override
public void start() {
System.out.println(“打开华为手机”);
}

@Override
public void close() {
    System.out.println("关闭华为手机");
}

@Override
public void call() {
    System.out.println("用华为手机打电话");
}

}

HuaweiRoute

public class HuaweiRoute implements RouteProduct {
@Override
public void start() {
System.out.println(“打开华为路由器”);
}

@Override
public void close() {
    System.out.println("关闭华为路由器");
}

@Override
public void connectwifi() {
    System.out.println("连接华为路由器");
}

}

XiaomiFactory

public class XiaomiFactory implements ProductFactory {
    @Override
    public PhoneProduct phoneProduct() {
        return new XiaomiPhone();
    }

    @Override
    public RouteProduct routeProduct() {
        return new XiaomiRoute();
    }
}

XiaomiPhone

public class XiaomiPhone implements PhoneProduct {
    @Override
    public void start() {
        System.out.println("打开小米手机");
}

    @Override
    public void close() {
        System.out.println("关闭小米手机");
    }

    @Override
    public void call() {
        System.out.println("用小米手机打电话");
    }
}

XiaomiRoute

public class XiaomiRoute implements RouteProduct {
    @Override
    public void start() {
        System.out.println("打开小米路由器");
    }

    @Override
    public void close() {
        System.out.println("关闭小米路由器");
    }

    @Override
    public void connectwifi() {
        System.out.println("连接小米路由器");
    }
}

Client

在这里插入代码片
public class Client {
    public static void main(String[] args) {
        System.out.println("=============小米产品================");
        XiaomiFactory xiaomiFactory=new XiaomiFactory();
        PhoneProduct phoneProduct1 = xiaomiFactory.phoneProduct();
        phoneProduct1.call();
        phoneProduct1.close();
        RouteProduct routeProduct1 = xiaomiFactory.routeProduct();
        routeProduct1.connectwifi();
        routeProduct1.close();


        System.out.println("=============华为产品================");
        HuaweiFactory huaweiFactory=new HuaweiFactory();
        PhoneProduct phoneProduct2 = huaweiFactory.phoneProduct();
        phoneProduct1.start();
        phoneProduct2.close();
        RouteProduct routeProduct2 = huaweiFactory.routeProduct();
        routeProduct2.connectwifi();
        routeProduct2.close();

    }
}

代理模式

1.1 静态代理模式
已中介租房来举例,本来你可以直接和房东谈,但是房东为了省事,把事情交付给中介。
在这里插入图片描述
接口Rent

public interface Rent {
    void rent();
}

Host

public class Host implements Rent{
    @Override
    public void rent() {
        System.out.println("房东要出租房子");
    }
}

Proxy

ublic class Proxy implements Rent{
    private Host host;

    public Proxy(){

}
    public Proxy(Host host) {
        this.host = host;
    }

    @Override
    public void rent() {
        host.rent();
        seeHouse();
        hetong();
        fare();
    }
    //看房
    public void seeHouse(){
        System.out.println("中介带你看房");
    }

    //签合同
    public void hetong(){
        System.out.println("签租赁合同");
    }
    //收中介费
    public void fare(){
        System.out.println("收取中介费");
    }
}

Client

public class Client {
    public static void main(String[] args) {
       Host host=new Host();
       //不面对房东,面对中介去租房
        Proxy proxy = new Proxy(host);
        proxy.rent();
    }
}

1.2 动态代理模式,代理不再是一个实体类
在这里插入图片描述
Rent

public interface Rent {
    void rent();
}

Host

public class Host implements Rent {
    @Override
    public void rent() {
        System.out.println("房东要出租房子");
    }
}

ProxyInvocationHandler

public class ProxyInvocationHandler implements InvocationHandler {
    //被代理的接口
    private Rent rent;

    public void setRent(Rent rent){
        this.rent=rent;
    }

    //生成得到代理类

    public Object getProxy(){
       return Proxy.newProxyInstance(this.getClass().getClassLoader(),rent.getClass().getInterfaces(),this);
    }
    @Override
    public Object invoke(Object o, Method method, Object[] args) throws Throwable {
        //动态代理的本质,就是使用放射机制实现!
        seeHouse();
        Object result=method.invoke(rent,args);
        return result;
    }
    public void seeHouse(){
        System.out.println("带你看房子");
    }
}

Client

public class Client {
    public static void main(String[] args) {
        //真实角色
        Host host=new Host();
        //代理角色:现在没有
        ProxyInvocationHandler pih=new ProxyInvocationHandler();
        //通过调用程序处理角色来处理我们要调用的接口对象!
        pih.setRent(host);
        Rent proxy=(Rent) pih.getProxy();//这里的Proxy就是动态深层
        proxy.rent();
    }
}

装饰者模式

以咖啡点单为例,在点咖啡时,可以加上相应的配料,而一种咖啡可以加多种配料,如果写在一起的话会有非常多的排列组合,所以这里用到装饰者模式,将配料作为装饰类来装饰咖啡。
在这里插入图片描述
让配料和咖啡都去继承Drink类,之后不同的配料和咖啡品种再去继承配料和咖啡。

Drink

public abstract class Drink {
    public String des;
    private float price;

    public String getDes() {
        return des;
    }

    public void setDes(String des) {
        this.des = des;
    }

    public float getPrice() {
        return price;
    }

    public void setPrice(float price) {
        this.price = price;
    }

    //计算费用的抽象方法
    public abstract float cost();
}

Coffee

public class Coffee extends Drink{

    @Override
    public float cost() {
        return super.getPrice();
    }
}

Decorator

public class Decorator extends Drink {
    private Drink obj;
    public Decorator(Drink obj){
        this.obj=obj;
    }
    @Override
    public float cost() {
        return super.getPrice()+obj.cost();
    }

    public String getDes(){
        return super.des+""+super.getPrice()+obj.getDes() ;
    }
}

LongBlack

ublic class LongBlack extends Coffee{

    public LongBlack(){
        setDes("黑咖啡");
        setPrice(12.0f);
    }
}

ShortBlack

public class ShortBlack extends Coffee{
    public ShortBlack(){
        setDes("美式咖啡");
        setPrice(18.0f);
    }
}

Chocolate

public class Chocolate extends Decorator{
    public Chocolate(Drink obj) {
        super(obj);
        setDes("巧克力调味品");
        setPrice(7.0f);
    }
}

Milk

public class Milk extends Decorator{
    public Milk(Drink obj) {
        super(obj);
        setDes("牛奶");
       setPrice(5.0f);
    }
}

CoffeeBar

public class CoffeeBar {
    public static void main(String[] args) {
        //装饰者模式下,点2份巧克力,一份牛奶longBlack
        Drink order=new LongBlack();
        System.out.println(order.cost()+"元");

        //加牛奶
        order=new Milk(order);
        System.out.println(order.getDes());
        System.out.println(order.cost());
        //加巧克力
        order=new Chocolate(order);
        System.out.println(order.cost());
        //再加巧克力
        order=new Chocolate(order);
        System.out.println(order.cost());
    }
}

这样在增加额外的单品咖啡或者配料时就不会影响太多的代码。

观察者模式

以气象台天气预报为例,气象台更新天气预报之后,各能把消息推送给各大平台,实现代码之间的低耦合,使用了观察者模式,各大平台为一个个观察者,写一个类WeatherData来对信息进行推送和对观察者进行管理。

在这里插入图片描述
Observer接口

public interface Observer {
    public void update(double temperatrue,double pressure,double humidity);

}

Subject接口

public interface Subject {
    public void registerObserver(Observer observer);
    public void remove(Observer observer);
    public void notifyObservers();
}

CurrentCondition

public class CurrentCondition implements Observer{
    private double temperatrue;
    private double pressure;
    private double humidity;

    @Override
    public void update(double temperatrue, double pressure, double humidity) {
        this.temperatrue=temperatrue;
        this.pressure=pressure;
        this.humidity=humidity;
        diplay();
    }

    public void diplay() {
        System.out.println("现在的气温是:"+temperatrue);
        System.out.println("现在的气压是:"+pressure);
        System.out.println("现在的湿度是:"+humidity);
    }
}

WeatherData

public class WeatherData implements Subject{
    private double temperatrue;
    private double pressure;
    private double humidity;
    private ArrayList<Observer> observers;

    public WeatherData(){
        observers=new ArrayList<Observer>();
    }

    public double getTemperatrue() {
        return temperatrue;
    }

    public void setTemperatrue(double temperatrue) {
        this.temperatrue = temperatrue;
    }

    public double getPressure() {
        return pressure;
    }

    public void setPressure(double pressure) {
        this.pressure = pressure;
    }

    public double getHumidity() {
        return humidity;
    }

    public void setHumidity(double humidity) {
        this.humidity = humidity;
    }

    public void dataChange(){
   notifyObservers();
    }
    //数据更新时用
    public void setdate(double temperatrue, double pressure, double humidity) {
        this.temperatrue=temperatrue;
        this.pressure=pressure;
        this.humidity=humidity;
      dataChange();
    }
    //注册
    @Override
    public void registerObserver(Observer observer) {
  observers.add(observer);
    }

    @Override
    public void remove(Observer observer) {
        if (observers.contains(observer)) {
            observers.remove(observer);
        }
    }

    @Override
    public void notifyObservers() {
  for (int i=0;i<observers.size();i++)
      observers.get(i).update(this.temperatrue,this.pressure,this.humidity);
    }
}

Baidu

public class Baidu implements Observer{
    private double temperatrue;
    private double pressure;
    private double humidity;

    @Override
    public void update(double temperatrue, double pressure, double humidity) {
        this.temperatrue=temperatrue;
        this.pressure=pressure;
        this.humidity=humidity;
        diplay();
    }


    public void diplay() {
        System.out.println("现在的百度气温是:"+temperatrue);
        System.out.println("现在的百度气压是:"+pressure);
        System.out.println("现在的百度湿度是:"+humidity);
    }
}

Client

public class Client {
    public static void main(String[] args) {
        WeatherData weatherData=new WeatherData();
        //创建观察者
        CurrentCondition currentCondition1 = new CurrentCondition();
        //注册到weatherData
        weatherData.registerObserver(currentCondition1);
        weatherData.setdate(10,20,30);
        //额外添加一个观察者
        Baidu baidu=new Baidu();
        weatherData.registerObserver(baidu);
        weatherData.setdate(30,50,100);


    }

}

职责链模式

例子:一个项目,职责越高的人可以动用的资金就更多,但输入一个金额时,查看应该有谁来处理。
在这里插入图片描述
Approver

public abstract class Approver {
    Approver approver;//下一个处理者
    String name;//名字

    public Approver(String name){
        this.name=name;
    }
    //下一个处理者
    public void setApprover(Approver approver){
        this.approver=approver;
    }
    //处理审批请求的方法,得到一个请求,子类来完成
    public abstract void processRequest(PurchaseRequest purchaseRequest);
}

PurchaseRequest

public class PurchaseRequest {
    private int type;//请求类型
    private float price;
    private int id;

    public PurchaseRequest(int type, float price, int id) {
        this.type = type;
        this.price = price;
        this.id = id;
    }

    public int getType() {
        return type;
    }

    public float getPrice() {
        return price;
    }

    public int getId() {
        return id;
    }
}

CollegeApprover

public class CollegeApprover extends Approver{
    public CollegeApprover(String name) {
        super(name);
    }

    @Override
    public void processRequest(PurchaseRequest purchaseRequest) {
        if (purchaseRequest.getPrice()>5000&&purchaseRequest.getPrice()<=10000){
            System.out.println("请求编号id="+purchaseRequest.getId()+"被"+this.name+"处理");
        }else {
            approver.processRequest(purchaseRequest);
        }
    }
}

DepartmentApprover

public class DepartmentApprover extends Approver{

    public DepartmentApprover(String name) {
        super(name);
    }

    @Override
    public void processRequest(PurchaseRequest purchaseRequest) {
        if (purchaseRequest.getPrice()<=5000){
            System.out.println("请求编号id="+purchaseRequest.getId()+"被"+this.name+"处理");
        }else {
            approver.processRequest(purchaseRequest);
        }
    }
}

ViceSchoolMasterApprover

public class ViceSchoolMasterApprover extends Approver{
    public ViceSchoolMasterApprover(String name) {
        super(name);
    }

    @Override
    public void processRequest(PurchaseRequest purchaseRequest) {
        if (purchaseRequest.getPrice()>10000&&purchaseRequest.getPrice()<=30000){
            System.out.println("请求编号id="+purchaseRequest.getId()+"被"+this.name+"处理");
        }else {
            approver.processRequest(purchaseRequest);
        }
    }
}

SchoolMasterApprover

public class SchoolMasterApprover extends Approver {
    public SchoolMasterApprover(String name) {
        super(name);
    }

    @Override
    public void processRequest(PurchaseRequest purchaseRequest) {
        if (purchaseRequest.getPrice()>=30000){
            System.out.println("请求编号id="+purchaseRequest.getId()+"被"+this.name+"处理");
        }else {
            approver.processRequest(purchaseRequest);
        }
    }
}

Client

public class Client {
    public static void main(String[] args) {
        //创建一个请求
        PurchaseRequest purchaseRequest = new PurchaseRequest(1, 31000, 1);
        //创建相关的审批人
        DepartmentApprover departmentApprover=new DepartmentApprover("主任");
        CollegeApprover collegeApprover=new CollegeApprover("院长");
        ViceSchoolMasterApprover viceSchoolMasterApprover=new ViceSchoolMasterApprover("副校长");
        SchoolMasterApprover schoolMasterApprover=new SchoolMasterApprover("校长");

        //将每个审批的下一个级别设置好
        departmentApprover.setApprover(collegeApprover);
        collegeApprover.setApprover(viceSchoolMasterApprover);
        viceSchoolMasterApprover.setApprover(schoolMasterApprover);
        schoolMasterApprover.setApprover(departmentApprover);
        departmentApprover.processRequest(purchaseRequest);
    }
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值