您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
在Java中,设计模式提供了一种可重用的解决方案框架,用于解决常见的编程问题。设计模式主要可以分为三大类:创建型模式、结构型模式和行为型模式。下面是如何利用Java对象实现一些常见设计模式的简要说明:
创建型模式主要关注对象的创建过程,将对象的创建与使用分离,从而增加系统的灵活性和复用性。
public class Singleton {
private static Singleton instance;
private Singleton() {}
public static synchronized Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}
public interface Product {
void use();
}
public class ConcreteProduct implements Product {
@Override
public void use() {
System.out.println("Using ConcreteProduct");
}
}
public abstract class Creator {
public abstract Product factoryMethod();
}
public class ConcreteCreator extends Creator {
@Override
public Product factoryMethod() {
return new ConcreteProduct();
}
}
结构型模式关注类和对象的组合与结构,以形成更大的结构。
public interface Target {
void request();
}
public class Adaptee {
public void specificRequest() {
System.out.println("Called specificRequest()");
}
}
public class Adapter implements Target {
private Adaptee adaptee;
public Adapter(Adaptee adaptee) {
this.adaptee = adaptee;
}
@Override
public void request() {
adaptee.specificRequest();
}
}
public interface Component {
void operation();
}
public class ConcreteComponent implements Component {
@Override
public void operation() {
System.out.println("ConcreteComponent operation");
}
}
public class Decorator implements Component {
private Component component;
public Decorator(Component component) {
this.component = component;
}
@Override
public void operation() {
component.operation();
}
// Add new behavior here
}
行为型模式关注算法和对象间的通信。
import java.util.ArrayList;
import java.util.List;
public class Subject {
private List<Observer> observers = new ArrayList<>();
public void addObserver(Observer observer) {
observers.add(observer);
}
public void removeObserver(Observer observer) {
observers.remove(observer);
}
public void notifyObservers() {
for (Observer observer : observers) {
observer.update();
}
}
}
public interface Observer {
void update();
}
public class ConcreteObserver implements Observer {
private String name;
public ConcreteObserver(String name) {
this.name = name;
}
@Override
public void update() {
System.out.println(name + " has been notified");
}
}
public interface Strategy {
int doOperation(int num1, int num2);
}
public class ConcreteStrategyA implements Strategy {
@Override
public int doOperation(int num1, int num2) {
return num1 + num2;
}
}
public class ConcreteStrategyB implements Strategy {
@Override
public int doOperation(int num1, int num2) {
return num1 * num2;
}
}
public class Context {
private Strategy strategy;
public void setStrategy(Strategy strategy) {
this.strategy = strategy;
}
public int executeStrategy(int num1, int num2) {
return strategy.doOperation(num1, num2);
}
}
以上只是设计模式的一些基本示例。在实际项目中,你可以根据需要灵活运用这些设计模式来提高代码的可维护性、可扩展性和可读性。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。