后端研发工程师面经——手撕设计模式

8. 手撕设计模式

8.1 手撕单例模式
  • 单例模式:保证一个类仅有一个实例,并提供一个访问它的全局访问点。
8.1.1 懒汉式线程不安全
  • 懒汉式单例模式 只是声明对象,等到调用getInstanc()的时候才进行new 对象 因为他懒
class lazyUnsafe {
    private static lazyUnsafe lazyUnsafe;

    private lazyUnsafe(){//new 实例的时候会调用这个构造方法
      System.out.println(Thread.currentThread().getName());
    }

    public static lazyUnsafe getInstance() {
        if (lazyUnsafe == null) {
            //这里的线程不安全 就是发生在这里 如果 A线程执行到这里 正好被阻塞了
            //然后CPU的时间片切换到B线程 然后B线程 new 了一个实例 那么的话
            //当CPU再次切换到A线程的时候,那么的话就又会new了一个实例 这样就破坏了单实例
            //
            lazyUnsafe = new lazyUnsafe();
        }
        return lazyUnsafe;
    }

    public static void main(String[] args) {
      for (int i = 0; i < 10; i++) {
          new Thread( ()->{
              lazyUnsafe.getInstance();//这里运行出几个线程  那就创造出几个实例 破坏了单例原则
          }                           // 在new lazyUnsafe()的时候  会调用空参构造方法,那么就会输出线程名
          ).start();
      }
}  
8.1.2 懒汉式线程安全
class lazysafe {
    private static lazySafe lazysafe;

    private lazySafe(){
        System.out.println(Thread.currentThread().getName());
    }

    public static synchronized lazySafe getInstance() {
        if (lazysafe == null) {
            lazysafe = new lazySafe();
        }
        return lazyUnsafe;
    }

    public static void main(String[] args) {
        for (int i = 0; i < 10; i++) {
            new Thread( ()-> {
                lazySafe.getInstance();//虽然我们开启了10个线程
                                        //但是只有一个线程可以new LazyUnsafe() 调用构造方法输出线程名
            }).start();                  //同一个在堆中new出的实例,那么后面的线程调用方法getInstance()的话  
          }                                   //因为 lazyUnsafe != null 了 所以不会再 new 实例了
        }
    }
}
8.1.3 双重检验
  • 第一个if语句,用来确认调用getInstance()时instance是否为空,如果不为空即已经创建,则直接返回,如果为空,那么就需要创建实例,于是进入synchronized同步块。
  • synchronized加类锁,确保同时只有一个线程能进入,进入以后进行第二次判断,是因为对于首个拿锁者,它的时段instance肯定为null,那么进入new Singleton()对象创建,在首个拿锁者的创建对象期间,可能有其他线程同步调用getInstance(),那么它们也会通过if进入到同步块试图拿锁然后阻塞(因为这时首拿锁的线程还在创建对象期间)。
  • 这样的话,当首个拿锁者完成了对象创建,之后的线程都不会通过第一个if了,而这期间阻塞的线程开始唤醒,它们则需要靠第二个if语句来避免再次创建对象。
  • 以上就是双检索的实现思路,synchronized与第二个if即是用来保证线程安全与不产生第二个实例
//双层锁的机制
public class SingleLazyDCL {

    private volatile static SingleLazyDCL singleLazyDCL;

    private SingleLazyDCL (){
        System.out.println(Thread.currentThread().getName());
    }

    public static SingleLazyDCL getInstance() {
        if (singleLazyDCL == null) {
            synchronized (SingleLazyDCL.class) {
                if (singleLazyDCL == null) {
                    singleLazyDCL = new SingleLazyDCL();
                }
            }
        }
        return singleLazyDCL;
    }

    public static void main(String[] args) {
        for (int i = 0; i < 10; i++) {
            new Thread( ()->{
                SingleLazyDCL.getInstance();
            }).start();
        }

    }

}
8.1.4 饿汉式
public class SingleHungry {
    private static SingleHungry singleHungry = new SingleHungry();

    private SingleHungry(){
        System.out.println(Thread.currentThread().getName());
    }

    public static SingleHungry getInstance() {
        return singleHungry;
    }

    public static void main(String[] args) {
        for (int i = 0; i < 10; i++) {
            new Thread( ()->{
                SingleHungry.getInstance();//这里不会输出构造器当中的方法了
            }).start();                   //因为调用该类的静态方法的时候,该类已经 n
        }                                //new 完实例了  那么我们就可以知道的是
    }                                   //那就没法再去 输出我们线程的名字    
}
8.2 手撕生产者消费者模式
  • 生产者消费者问题是一个多线程同步的经典问题,这个问题描述了生产者线程和消费者线程共享固定大小的缓冲区的问题。生产者不断的向缓冲区添加数据,消费者不断的消费缓冲区的数据,这个问题的关键是:
  • 保证生产者在缓冲区满的时候不再向缓冲区添加数据,消费者在缓冲区空的时候也不会的时候消费缓冲区数据
  • 解决思路:
    • 生产者不断的生产,直到缓冲区满的时候,阻塞生产者线程,缓冲区不满的时候,继续生产
    • 消费者不断的消费,直到缓冲区空的时候,阻塞消费者线程,缓冲区不空的时候,继续消费
public class ProducerAndConsumer {

    //消费者
    static class Consumer implements Runnable {
        private List<Integer> queue;

        public Consumer(List<Integer> queue) {
            this.queue = queue;
        }

        @Override
        public void run() {
            try {
                while (true) {
                    synchronized (queue) {
                        while (queue.isEmpty()) {
                            System.out.println("Queue is Empty");
                            queue.wait();
                        }
                        int i = queue.remove(0);
                        queue.notifyAll();
                        System.out.println(Thread.currentThread().getName() + "消费了:" + i + "还剩:" + queue.size());
                        Thread.sleep(100);
                    }
                }
            } catch (InterruptedException e) {

            }

        }
    }

    //生产者
    static class Producer implements Runnable {

        private List<Integer> queue;

        private int length; //容量

        public Producer(List<Integer> queue, int length) {
            this.queue = queue;
            this.length = length;
        }

        @Override
        public void run() {
            try {
                while (true) {
                    synchronized (queue) {
                        while (queue.size() > length) {
                            queue.wait();
                        }
                        queue.add(1);
                        System.out.println(Thread.currentThread().getName() + "生产了" + 1 + "现在有" + queue.size());
                        Thread.sleep(100);
                        queue.notifyAll();
                    }
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        List<Integer> queue = new ArrayList<>();
        int length = 10;
        ExecutorService service = Executors.newCachedThreadPool();
        service.execute(new Producer(queue, 10));
        service.execute(new Producer(queue, 10));
        service.execute(new Producer(queue, 10));
        service.execute(new Consumer(queue));
        service.execute(new Consumer(queue));
        service.execute(new Consumer(queue));
    }
}
8.3 手撕工厂模式
  • 在实际业务中我们经常创建对象,常用的做法就是new。但是有些情况下对new不做控制就会造成资源浪费,不能做到多路复用,而且很容易达到系统瓶颈。这个时候就可以考虑使用工厂模式。比如数据库连接资源,Redis连接资源、日志记录等场景。
/**
 * 电脑抽象类
 */
public interface Computer {

    /**
     * 制造电脑的方法
     */
    Computer make();
}

/**
 * 笔记本
 */
public class Laptop implements Computer {
    public Laptop() {
        System.out.println("make a Laptop Computer!");
    }

    @Override
    public Computer make() {
        return new Laptop();
    }
}

/**
 * 个人PC,台式机
 */
public class Desktop implements Computer {
    public Desktop() {
        System.out.println("make a Desktop Computer!");;
    }

    @Override
    public Desktop make() {
        return new Desktop();
    }
}


/**
 * 简单工厂模式
 */
public class ComputerSimpleFactory {
    Computer makeComputer(String computerType) {
        switch (computerType) {
            case "desktop":
                return new Desktop();
            case "laptop":
                return new Laptop();
        }
        return null;
    }

    public static void main(String[] args) {
        ComputerSimpleFactory computerSimpleFactory = new ComputerSimpleFactory();
        Computer desktop = computerSimpleFactory.makeComputer("desktop");
        Computer laptop = computerSimpleFactory.makeComputer("laptop");
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值