21xrx.com
2024-09-19 09:38:21 Thursday
登录
文章检索 我的文章 写文章
《掌握Java设计模式,提升代码质量》
2023-06-12 01:28:12 深夜i     --     --
Java 设计模式 代码实现

Java设计模式是指在软件设计中常见的重复问题的解决方案,这些解决方案经过了时间和实践的考验,在实际应用中得证有效。掌握Java设计模式可以提升代码的可读性、可维护性和可扩展性,大大提高软件的质量。

下面以最常见的23种设计模式为例,介绍它们的应用场景和代码实现。

1.单例模式(Singleton)

单例模式保证一个类只有一个实例,并提供一个全局的访问点。通常在需要全局访问时使用,比如配置信息类、线程池等。

代码实现:


public class Singleton { 

   private static Singleton instance = null; 

   private Singleton() {} 

   public static Singleton getInstance() { 

     if(instance == null) { 

       instance = new Singleton(); 

     } 

     return instance; 

   } 

}

2.工厂模式(Factory)

工厂模式定义一个创建对象的接口,但由子类决定要实例化哪一个类。将具体创建实例的工作推迟到子类中进行,可以避免在代码中使用new运算符。

代码实现:


public interface Vehicle { 

  void run(); 

public class Car implements Vehicle { 

  public void run() { 

    System.out.println("开车咯!"); 

  } 

public class Bus implements Vehicle { 

  public void run() { 

    System.out.println("坐公交!"); 

  } 

}

public interface VehicleFactory { 

  Vehicle createVehicle(); 

public class CarFactory implements VehicleFactory { 

  public Vehicle createVehicle() { 

    return new Car(); 

  } 

public class BusFactory implements VehicleFactory { 

  public Vehicle createVehicle() { 

    return new Bus(); 

  } 

}

public class Test { 

  public static void main(String[] args) { 

    VehicleFactory factory = new CarFactory(); 

    Vehicle car = factory.createVehicle(); 

    car.run(); 

  } 

}

3.适配器模式(Adapter)

适配器模式将一个类的接口转换成客户端所期望的另一个接口,使得原本由于接口不兼容而不能一起工作的类可以在一起工作。通常在系统后期扩展或整合不兼容的接口时使用。

代码实现:


public interface Target { 

  void request(); 

public class Adaptee { 

  public void specificRequest() { 

    System.out.println("Adaptee方法被调用!"); 

  } 

public class Adapter implements Target { 

  private Adaptee adaptee = new Adaptee(); 

  public void request() { 

    adaptee.specificRequest(); 

  } 

}

public class Test { 

  public static void main(String[] args) { 

    Target target = new Adapter(); 

    target.request(); 

  } 

}

  
  

评论区

{{item['qq_nickname']}}
()
回复
回复