我很难过你收到一堆反对票。从你的名声来看,你可能是个新手,只是抛出一堆你听过的技术术语,而实际上并不知道它们是什么。让我试着给你一个快速教程,然后也许你能更好地提出你的问题。
什么是单例模式?
单例模式是一种软件设计模式,它保证一个类只有一个实例,并且该类提供对它的全局访问点。每当多个类或客户端请求该类时,它们都会获得该类的相同实例。这个 Singleton 类可能负责实例化自己,或者您可以将对象创建委托给工厂类。
使用您的类之一的简单示例
public class PaymentRepository {
private static PaymentRepository INSTANCE = null;
// other instance variables can be here
private PaymentRepository() {};
public static PaymentRepository getInstance() {
if (INSTANCE == null) {
INSTANCE = new PaymentRepository();
}
return(INSTANCE);
}
// other instance methods can follow
}
请注意,构造函数是非静态和私有的,而 getInstance() 方法是静态和公共的。
关于策略模式,当类行为或其算法可以在运行时更改时使用。
什么是策略模式?
在策略模式中,我们创建表示各种策略的对象和一个其行为根据其策略对象而变化的上下文对象。策略对象改变上下文对象的执行算法。
从创建接口开始
public interface OperationStrategy {
public int doOperation(int num1, int num2);
}
创建实现该接口的具体类
public class OperationAddition implements OperationStrategy {
@Override
public int doOperation(int num1, int num2) {
return num1 + num2;
}
}
创建上下文类
public class Context {
private OperationStrategy strategy;
public Context(OperationStrategy strategy){
this.strategy = strategy;
}
public int executeStrategy(int num1, int num2){
return strategy.doOperation(num1, num2);
}
}
当它改变它的策略时,使用上下文来观察行为的变化。
public class StrategyPatternDemo {
public static void main(String[] args) {
Context context = new Context(new OperationAddition());
System.out.println("10 + 5 = " + context.executeStrategy(10, 5));
}
}