21xrx.com
2024-12-23 01:11:07 Monday
登录
文章检索 我的文章 写文章
Java设计模式详解:共有多少种设计模式?
2023-06-15 09:37:21 深夜i     --     --
Java

Design patterns are proven solutions to common programming problems that can be easily reused. These patterns can be used to design maintainable, stable, flexible, and reusable software applications. In Java, there are a total of 23 design patterns which are classified into three categories: Creational, Structural, and Behavioral patterns.

Creational patterns are used to create objects in a systematic way, allowing components to be easily added or replaced. There are five creational patterns in Java: Factory Method, Abstract Factory, Singleton, Builder, and Prototype.

Structural patterns are used to coordinate communication between different objects. They improve the overall efficiency and ease of use of the system. Some of the common structural patterns are Adapter, Bridge, Decorator, Composite, and Facade.

Behavioural design patterns are responsible for the interactions between different objects and focus on how objects communicate among themselves. These patterns help in organizing code in a more manageable and understandable way. Java has 12 behavioral patterns, such as Chain of Responsibility, Command, Interpreter, Iterator, Mediator, Memento, Observer, State, Strategy, Template Method, Visitor, and Null Object.

Here is an example of a creational pattern in Java:


public interface Shape {

  void draw();

}

public class Circle implements Shape {

  public void draw() {

   System.out.println("Drawing Circle");

  }

}

public class Square implements Shape {

  public void draw() {

   System.out.println("Drawing Square");

  }

}

public class ShapeFactory {

  public Shape getShape(String shapeType){

   if(shapeType == null)

     return null;

   

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

     return new Circle();

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

     return new Square();

   }

   return null;

  }

}

//Client code

public class Client {

  public static void main(String[] args) {

   ShapeFactory shapeFactory = new ShapeFactory();

   //get an object of Circle class and call its draw method.

   Shape shape1 = shapeFactory.getShape("CIRCLE");

   //call draw method of Circle

   shape1.draw();

   //get an object of Square class and call its draw method.

   Shape shape2 = shapeFactory.getShape("SQUARE");

   //call draw method of circle

   shape2.draw();

  }

}

Design patterns, Creational patterns.

  
  

评论区

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