什么时候使用策略或门面?

When to use strategy or facade?

所以我和我的小组正在研究这个房地产项目(学校作业),如果我们使用了错误的策略模式,我们会感到很困扰,应该改用 Facade。我正在为数据库的 CRUD 编写代码,我使用策略模式从 jform 调用那些 CRUD 方法(添加、删除、更新)。我们仍在开始学习不同的设计模式,所以如果这是一个正确的实现,我们愿意提供帮助。

这是我的策略模式代码

public interface methods {
    public void doOperation(int id, String type, int area, String address, String listingStatus);
}

public class methodUse {
    private methods method;

    public methodUse(methods method) {
        this.method = method;
    }
    
    public void executeMethod(int id, String type, int area, String address, String listingStatus){
         method.doOperation(id, type, area, address, listingStatus);
    }
}

public class methodUpdate implements methods{
    private SystemAdmin systemAdmin = new SystemAdmin();

    @Override
    public void doOperation(int id, String type, int area, String address, String listingStatus) {
        systemAdmin.updatePropertyListing(id, listingStatus);
    
    }
}

public class methodDelete implements methods{
   private SystemAdmin systemAdmin = new SystemAdmin();


    @Override
    public void doOperation(int id, String type, int area, String address, String listingStatus) {
      systemAdmin.deleteListing(id);
    }
}

public class methodAdd implements methods{
    private SystemAdmin systemAdmin = new SystemAdmin();

    @Override
    public void doOperation(int id, String type, int area, String address, String listingStatus) {
        systemAdmin.addListing(id, type, area, address, listingStatus);
    }
    
}

每次单击特定按钮时都会在 jform 上调用 类,例如。添加按钮执行策略添加。

我想问问大家,我们所做的是否是策略模式的正确实现。

问:什么时候应该使用“策略”模式?

https://refactoring.guru/design-patterns/strategy

Use the Strategy pattern when you want to use different variants of an algorithm within an object and be able to switch from one algorithm to another during runtime.

所以在这种情况下,您选择“策略”模式并没有“错”

问:[是]我们所做的是战略模式的正确实施吗?

  • Declare the strategy interface common to all variants of the algorithm.

  • One by one, extract all algorithms into their own classes. They should all implement the strategy interface.

是的,你已经正确实施了它。

问:那么“门面”呢?

正如 John Bollinger 所说:

The Strategy and Facade patterns are not alternatives to each other. It is plausible that a program might use both. Nor is there generally a single correct answer to how to design a program or which design patterns might be useful in it.