欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

设计模式

程序员文章站 2022-06-28 19:09:46
这幅图清晰的表达了6大设计原则,但他仅限于叫什么名字而已,他们具体什么意思呢?下面我们将从原文、译文、理解、应用,这四个方面进行阐述。 1.单一职责原则(Single Responsibility Principle - SRP) 2.开放封闭原则(Open Closed Principle - O ......

设计模式

单例模式

单例模式概述:

能使用一个对象来做就不用实例化多个对象!这就能减少我们空间和内存的开销~

那有可能有的人又会想了:我们使用静态类.doSomething()和使用单例对象调用方法的效果是一样的啊。

  • 没错,效果就是一样的。使用静态类.doSomething()体现的是基于对象,而使用单例设计模式体现的是面向对象

编写单例模式的代码其实很简单,就分了三步:

  • 将构造函数私有化
  • 在类的内部创建实例
  • 提供获取唯一实例的方法

饿汉式单例:

 //饿汉式单例
public class Hungry {
    
// 1.将构造函数私有化,不可以通过new的方式来创建对象
    private Hungry(){

    }
    //    直接上来就new,static 万一用不到,浪费内存
    private final static Hungry HUNGRY = new Hungry();

    public static Hungry getInstance(){
        return HUNGRY;
    }
}

懒汉式单例:

//懒汉式单例
public class LazyMan {
    
 // 1.将构造函数私有化,不可以通过new的方式来创建对象
    private LazyMan(){
        System.out.println(Thread.currentThread().getName() + " OK");

    }
    private volatile static LazyMan lazyMan = null;

    //双重检测锁模式的 懒汉式单例 DCL懒汉式
    public static LazyMan getInstance(){
        if(lazyMan == null){
            synchronized (LazyMan.class){
                if(lazyMan == null){
                    lazyMan = new LazyMan();
                }
            }
        }
        return lazyMan;
    }
    // //    单线程没问题,多线程并发下有问题 如下
    // public static void main(String[] args) {
    //     for (int i = 0; i < 10; i++) {
    //         new Thread(()->{
    //             LazyMan.getInstance();
    //         }).start();
    //     }
    // }
}

代码仍有问题,用反射可以破坏单例

    public static void main(String[] args) throws Exception {
        LazyMan instance = LazyMan.getInstance();
        
        //用反射来破坏单例
        Constructor<LazyMan> declaredConstructor = LazyMan.class.getDeclaredConstructor(null);
        declaredConstructor.setAccessible(true);

        LazyMan instance1 = declaredConstructor.newInstance();

        System.out.println(instance);
        System.out.println(instance1);

    }

解决办法:

静态内部类实现单例:

public class LazyHolder {

    private LazyHolder(){
        System.out.println(Thread.currentThread().getName() + " OK");
    }
    //使用内部类来实现懒加载
    private static class Holder{
        //创建单例对象
        private static final LazyHolder INSTANCE = new LazyHolder();

    }

    //获取对象
    public static final LazyHolder getInstance(){
        return Holder.INSTANCE;
    }
    
   
    public static void main(String[] args) {
        for (int i = 0; i < 10; i++) {
            new Thread(()->{
                LazyHolder.getInstance();
            }).start();
        }
    }
}

枚举类实现单例:

public enum  EnumSingle {

    INSTANCE;

    public EnumSingle getInstance(){
        return INSTANCE;
    }
}

总结:

总的来说单例模式写法有5种:

  • 饿汉式
  • 简单懒汉式(在方法加锁)
  • DCL双重检测加锁(进阶懒汉式)
  • 静态内部类实现懒汉式(最推荐写法)
  • 枚举方式(最安全、简洁写法)

工厂模式

简单工厂模式:

又叫静态工厂模式

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-kU64BaGx-1611112365374)(C:\Users\IT\AppData\Roaming\Typora\typora-user-images\image-20201224142330093.png)]


public interface Car {

    void name();

}

public class WuLin implements Car {
    @Override
    public void name() {
        System.out.println("五菱宏光!!");
    }
}

public class TeSiLa implements Car {
    @Override
    public void name() {
        System.out.println("特斯拉!!!");
    }
}

//静态工厂模式
//简单工厂模式
public class CarFactory {
    public static Car getCar(String car){
        if(car.equals("五菱")){
            return new WuLin();
        }else if(car.equals("特斯拉")){
            return new TeSiLa();
        }else {
            return null;
        }
    }
}

public class Consumer {
    public static void main(String[] args) {
        //接口,所有实现类!!相当于工厂
        // WuLin car = new WuLin();
        // TeSiLa car1 = new TeSiLa();

        //使用工厂创建
        Car car = CarFactory.getCar("五菱");
        Car car1 = CarFactory.getCar("特斯拉");

        car.name();
        car1.name();

    }
}


工厂方法模式:

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-TPY3hrNg-1611112365377)(C:\Users\IT\AppData\Roaming\Typora\typora-user-images\image-20201224142639319.png)]

public interface Car {

    void name();

}

public interface CarFactory {

    Car getCar();
}

WuLin.class和TeSiLa.class同上
    
 public class TeSiLaFactory implements CarFactory {
    @Override
    public Car getCar() {
        return new TeSiLa();
    }
}

public class WuLinFactory implements CarFactory {
    @Override
    public Car getCar() {
        return new WuLin();
    }
}

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

        car1.name();
        car2.name();

        Car car3 = new MoBaiFactory().getCa();
        car3.name();
    }
}



抽象工厂模式:

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-sytUcTAn-1611112365379)(C:\Users\IT\AppData\Roaming\Typora\typora-user-images\image-20201224143614790.png)]

public interface IRouterProduct {

    void start();
    void shutdown();
    void openWifi();
    void setParam();

}

public interface IPhoneProduct {

    void start();
    void shutdown();
    void callup();
    void sendSMS();
}

//抽象产品工厂
public interface IProductFactory {

    //生长手机的工厂
    IPhoneProduct I_PHONE_PRODUCT();

    //生产路由器的工厂
    IRouterProduct I_ROUTER_PRODUCT();

    //生产电脑的工厂
    IComputerProduct I_COMPUTER_PRODUCT();

}

public class HuaWeiFactory implements IProductFactory {
    @Override
    public IPhoneProduct I_PHONE_PRODUCT() {
        return new HuaWeiPhone();
    }

    @Override
    public IRouterProduct I_ROUTER_PRODUCT() {
        return new HuaWeiRoute() ;
    }

    @Override
    public IComputerProduct I_COMPUTER_PRODUCT() {
        return new HuaWeiComputer();
    }
}

public class XiaoMiFactory implements IProductFactory {
    @Override
    public IPhoneProduct I_PHONE_PRODUCT() {
        return new XiaoMiPhone();
    }

    @Override
    public IRouterProduct I_ROUTER_PRODUCT() {
        return new XiaoMiRoute();
    }

    @Override
    public IComputerProduct I_COMPUTER_PRODUCT() {
        return new XiaoMiComputer();
    }
}

public class XiaoMiPhone implements IPhoneProduct {
    @Override
    public void start() {
        System.out.println("小米开机!!!!");
    }

    @Override
    public void shutdown() {
        System.out.println("小米关机!!!!");
    }

    @Override
    public void callup() {
        System.out.println("小米打电话~~~~");
    }

    @Override
    public void sendSMS() {
        System.out.println("小米发消息~~~~~");
    }
}

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

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

    @Override
    public void openWifi() {
        System.out.println("打开小米路由器无线");
    }

    @Override
    public void setParam() {
        System.out.println("配置小米路由器参数");
    }
}

public class Client {

    public static void main(String[] args) {
        System.out.println("=========小米系列产品============");

        XiaoMiFactory xiaoMiFactory = new XiaoMiFactory();
        IPhoneProduct xiaomi = xiaoMiFactory.I_PHONE_PRODUCT();


        xiaomi.start();
        xiaomi.callup();
        xiaomi.sendSMS();
        xiaomi.shutdown();

        IRouterProduct xiaomiRoute = xiaoMiFactory.I_ROUTER_PRODUCT();

        xiaomiRoute.start();
        xiaomiRoute.openWifi();
        xiaomiRoute.setParam();
        xiaomiRoute.shutdown();

        IComputerProduct xiaomiComputer = xiaoMiFactory.I_COMPUTER_PRODUCT();

        xiaomiComputer.start();
        xiaomiComputer.callup();
        xiaomiComputer.sendSMS();
        xiaomiComputer.shutdown();

        System.out.println("==========华为系列产品==========");

        HuaWeiFactory huaWeiFactory = new HuaWeiFactory();
        IPhoneProduct huawei = huaWeiFactory.I_PHONE_PRODUCT();

        huawei.start();
        huawei.callup();
        huawei.sendSMS();
        huawei.shutdown();

        IRouterProduct huaweiRoute = huaWeiFactory.I_ROUTER_PRODUCT();

        huaweiRoute.start();
        huaweiRoute.openWifi();
        huaweiRoute.setParam();
        huaweiRoute.shutdown();

        IComputerProduct huaweiComputer = huaWeiFactory.I_COMPUTER_PRODUCT();

        huaweiComputer.start();
        huaweiComputer.callup();
        huaweiComputer.sendSMS();
        huaweiComputer.shutdown();



    }
}













装饰模式

又叫包装模式

电话接口:
    public interface Phone{

    void call();
}

具体实现:
    public class IphoneX implements Phone {
    @Override
    public void call() {
        System.out.println("打电话");
    }
}

//装饰器   实现接口
public abstract class PhoneDecorate implements Phone {

    //以组合的方式实现默认实现类
    private Phone phone;

    public PhoneDecorate(Phone phone) {
        this.phone = phone;
    }

    @Override
    public void call() {
        phone.call();
    }
}

// 继承着装饰器来扩展
public class MusicPhone extends PhoneDecorate {

    public MusicPhone(Phone phone) {
        super(phone);
    }

    //定义想要扩展的功能
    public void listenMusic(){

        System.out.println("继续跑 带着赤子的骄傲,生命的闪耀不坚持到底怎能看到,与其苟延残喘不如纵情燃烧");
    }

    //重写打电话的方法
    @Override
    public void call(){

        listenMusic();
        super.call();
    }
}

public class GiveCurrentTimePhone extends PhoneDecorate {

    public GiveCurrentTimePhone(Phone phone) {
        super(phone);
    }

    // 自定义想要实现的功能:给出当前的时间
    public void currentTime() {
        System.out.println("当前的时间是:" + System.currentTimeMillis());
    }

    // 重写要增强的方法
    @Override
    public void call() {
        super.call();
        // 打完电话后通知一下当前时间
        currentTime();
    }
}

public class ren {

    public static void main(String[] args) {
        //创建出最原始的实现类
        Phone phone = new IphoneX();

        //装饰成打电话之前可以听音乐的功能
        phone = new MusicPhone(phone);

        //装饰成打电话之后可以通知当前时间的功能
        phone = new GiveCurrentTimePhone(phone);

        phone.call();

    }
}

策略模式

/**
 * 增加粉丝策略的接口(Strategy)
 */
interface IncreaseFansStrategy {

    void action();
}

public class OriginalArticle implements IncreaseFansStrategy {
    @Override
    public void action() {
        System.out.println("3y认真写原创,最新一篇文章:《策略模式,就这?》");
    }
}

public class WaterArmy implements IncreaseFansStrategy {
    @Override
    public void action() {
        System.out.println("3y牛逼,我要给你点赞、转发、加鸡腿!");
    }
}

public class ren {

    private IncreaseFansStrategy strategy;

    public ren(IncreaseFansStrategy strategy){
        this.strategy = strategy;
    }
    // ren要发文章了(买水军了、送书了、写知乎引流了...)。
    // 具体执行哪个,看ren选哪个
    public void exec(){
        strategy.action();
    }
}

public class Main {
    public static void main(String[] args) {
        ren ren = new ren(new WaterArmy());
        ren.exec();

        ren ren1 = new ren(new OriginalArticle());
        ren1.exec();
    }
}















.println(“3y牛逼,我要给你点赞、转发、加鸡腿!”);
}
}

public class ren {

private IncreaseFansStrategy strategy;

public ren(IncreaseFansStrategy strategy){
    this.strategy = strategy;
}
// ren要发文章了(买水军了、送书了、写知乎引流了...)。
// 具体执行哪个,看ren选哪个
public void exec(){
    strategy.action();
}

}

public class Main {
public static void main(String[] args) {
ren ren = new ren(new WaterArmy());
ren.exec();

    ren ren1 = new ren(new OriginalArticle());
    ren1.exec();
}

}


























本文地址:https://blog.csdn.net/weixin_45698945/article/details/112860466

相关标签: 设计模式 java