21xrx.com
2024-11-08 20:23:48 Friday
登录
文章检索 我的文章 写文章
《Java设计模式:掌握六大原则》
2023-06-17 17:25:00 深夜i     --     --
Java设计模式 原则 案例

Java设计模式是一个让程序员更好地编写高质量代码的工具。在设计模式中,有六大原则可以帮助我们设计出更加合理和高效的程序。下面我们会对这六大原则进行详细介绍,带上相应的代码案例。

1. 开闭原则

开闭原则是指在修改代码时,应该尽量避免对已有代码的修改,而是通过添加新的代码来扩展。这样的做法可以让我们的代码更加稳定,易于维护。


public interface Shape {

  void draw();

}

public class Circle implements Shape {

  @Override

  public void draw() {

    System.out.println("Draw circle");

  }

}

public class Rectangle implements Shape {

  @Override

  public void draw() {

    System.out.println("Draw rectangle");

  }

}

public class ShapeFactory {

  public Shape getShape(String shapeType){

    if(shapeType == null)

      return null;

    

    if(shapeType.equalsIgnoreCase("CIRCLE")){

      return new Circle();

    } else if(shapeType.equalsIgnoreCase("RECTANGLE")){

      return new Rectangle();

    }

    return null;

  }

}

2. 单一职责原则

单一职责原则是指一个类应该只有单一的功能,也就是说一个类应该只有一个引起它变化的原因,这样的做法可以让我们的代码更加健壮,易于维护。


public class Book {

  private String name;

  private String author;

  private int price;

  //constructor, getters and setters

  public String toString(){

    return "Book{name: " + this.name + ", author: " + this.author + ", price: " + this.price + "}";

  }

}

public class BookStore {

  private List books = new ArrayList ();

  public void addBook(Book book){

    books.add(book);

  }

  public void removeBook(Book book){

    books.remove(book);

  }

  public List searchBooksByAuthor(String author){

    List result = new ArrayList ();

    for(Book book: books){

      if(book.getAuthor().equalsIgnoreCase(author)){

        result.add(book);

      }

    }

    return result;

  }

  public List searchBooksByPrice(int minPrice, int maxPrice){

    List result = new ArrayList ();

    for(Book book: books){

      if(book.getPrice() >= minPrice && book.getPrice() <= maxPrice){

        result.add(book);

      }

    }

    return result;

  }

}

3. 里氏替换原则

里氏替换原则是指子类可以替换其父类并出现在父类能够出现的任何地方,而不会产生任何错误或异常,这样的设计可以让我们的代码更加灵活。


public class Shape {

  protected int width;

  protected int height;

  public Shape(){}

  public Shape(int width, int height)

    this.width = width;

    this.height = height;

  

  public int getWidth()

    return width;

  

  public void setWidth(int width)

    this.width = width;

  

  public int getHeight()

    return height;

  

  public void setHeight(int height)

    this.height = height;

  

  public int getArea()

    return 0;

  

}

public class Rectangle extends Shape {

  public Rectangle(){}

  public Rectangle(int width, int height){

    super(width, height);

  }

  @Override

  public int getArea() {

    return width * height;

  }

}

public class Square extends Shape {

  public Square(){}

  public Square(int side){

    super(side, side);

  }

  @Override

  public void setWidth(int width) {

    super.setWidth(width);

    super.setHeight(width);

  }

  @Override

  public void setHeight(int height) {

    super.setHeight(height);

    super.setWidth(height);

  }

  @Override

  public int getArea() {

    return width * height;

  }

}

4. 接口隔离原则

接口隔离原则是指一个类不应该强迫其它类依赖于它们不需要使用的方法,这样的设计可以让我们的代码更加简洁,易于扩展。


public interface Car {

  void start();

  void stop();

  void accelerate();

  void brake();

  void refuel();

}

public class ElectricCar implements Car {

  @Override

  public void start()

    //method body

  

  @Override

  public void stop()

    //method body

  

  @Override

  public void accelerate()

    //method body

  

  @Override

  public void brake()

    //method body

  

  @Override

  public void refuel()

    //method body

  

}

public class GasolineCar implements Car {

  @Override

  public void start()

    //method body

  

  @Override

  public void stop()

    //method body

  

  @Override

  public void accelerate()

    //method body

  

  @Override

  public void brake()

    //method body

  

  //refuel method is not applicable for this class

}

5. 依赖倒置原则

依赖倒置原则是指高层次的模块不应该依赖于低层次的模块,而是应该依赖于抽象,这样的设计可以让我们的代码更加灵活,易于扩展。


public interface Payment {

  void pay(double amount);

}

public class CreditCardPayment implements Payment {

  @Override

  public void pay(double amount)

    //method body

  

}

public class CashPayment implements Payment {

  @Override

  public void pay(double amount)

    //method body

  

}

public class Order {

  private double totalAmount;

  private Payment payment;

  

  public Order(double totalAmount, Payment payment)

    this.totalAmount = totalAmount;

    this.payment = payment;

  

  public void process() {

    payment.pay(totalAmount);

  }

}

6. 迪米特原则

迪米特原则是指一个对象应该对其它对象有尽可能少的了解,这样的设计可以让我们的代码更加简化,易于维护。


public class Client {

  public static void main(String[] args) {

    Amazon amazon = new Amazon();

    System.out.println(amazon.searchBooks("Java"));

  }

}

public class Amazon {

  private BookSearcher bookSearcher;

  public Amazon(){

    bookSearcher = new BookSearcher();

  }

  public List searchBooks(String keywords){

    return bookSearcher.search(keywords);

  }

}

public class Book {

  private String name;

  private String author;

  private int price;

  //constructor, getters and setters

  public String toString(){

    return "Book{name: " + this.name + ", author: " + this.author + ", price: " + this.price + "}";

  }

}

public class BookSearcher {

  public List search(String keywords)

    //method body

  

  private List fetchFromDatabase(String keywords)

    //method body

  

  private List fetchFromInternet(String keywords)

    //method body

  

}

  
  

评论区

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