【问题标题】:Create Singleton using Strategy Design Pattern - Android使用策略设计模式创建单例 - Android
【发布时间】:2020-01-17 16:41:54
【问题描述】:

我知道Singleton Design PatternStrategy Design PatternComposite Design Pattern 以及这些模式的用法。

我想要的是我想要一个唯一的方法(可能是静态的),它负责创建接受class 的对象并返回该class 的对象(如果已经创建,将返回单例对象)

例如,

class AuthRepository
class SettingRepository
class PaymentRepository
....

如何使用策略设计模式创建这些类的单例?

【问题讨论】:

    标签: java android kotlin


    【解决方案1】:

    我很难过你收到一堆反对票。从你的名声来看,你可能是个新手,只是抛出一堆你听过的技术术语,而实际上并不知道它们是什么。让我试着给你一个快速教程,然后也许你能更好地提出你的问题。

    什么是单例模式? 单例模式是一种软件设计模式,它保证一个类只有一个实例,并且该类提供对它的全局访问点。每当多个类或客户端请求该类时,它们都会获得该类的相同实例。这个 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));
       }
    }
    

    【讨论】:

    • 我可以使用策略模式创建一个类的实例吗?
    猜你喜欢
    • 1970-01-01
    • 2011-06-21
    • 2014-08-06
    • 1970-01-01
    • 2021-08-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多