简体   繁体   English

此解决方案的不同设计模式

[英]a different design pattern for this solution

I am having an interface that holds three different methods.我有一个包含三种不同方法的接口。 And there are two class Car and Plane which will implement the Vehicle interface to get access to those methods.并且有两个类 Car 和 Plane 将实现 Vehicle 接口来访问这些方法。 There are two questions that I have in my mind.我心中有两个问题。

1. What type of design pattern satisfies the following implementation? 1. 什么样的设计模式满足下面的实现?

2. Is there any other design pattern to satisfy similar kinds of functionalities? 2. 有没有其他设计模式可以满足类似的功能?

Though I have tried some blogs and questions I have found one answer regarding the second question which is using Anonymous Class but which leads to more garbage code.尽管我尝试了一些博客和问题,但我找到了关于第二个问题的答案,该问题使用匿名类但会导致更多垃圾代码。 So is there any solution or answer to my questions?那么我的问题有什么解决方案或答案吗?

public interface Vehicle {
    int set_num_of_wheels();
    int set_num_of_passengers();
    boolean has_gas();
}
public class Car implements Vehicle{

    @Override
    public int set_num_of_wheels() {
        return 0;
    }

    @Override
    public int set_num_of_passengers() {
        return 0;
    }

    @Override
    public boolean has_gas() {
        return true;
    }

}

public class Plane implements Vehicle{

    @Override
    public int set_num_of_wheels() {
        return 0;
    }

    @Override
    public int set_num_of_passengers() {
        return 0;
    }

    @Override
    public boolean has_gas() {
        return true;
    }

}

Polymorphism is just a fancy way to put different function pointers (chosen inconditionally by the concrete class) under a given function name.多态只是将不同的函数指针(由具体类无条件选择)放在给定函数名下的一种奇特方式。

So instead if you had a single class with a hashmap of methodenum-to-somefunctioninterface (method enum would just list the finite set of methods to hookup), then you could call the polymorphic functions by looking them up by the enum in the map, then casting to somefunctioninterface and calling it.因此,如果您有一个带有 methodenum-to-somefunctioninterface 哈希映射的类(方法枚举只会列出要连接的有限方法集),那么您可以通过在映射中通过枚举查找来调用多态函数,然后投射到某个函数接口并调用它。

It entirely defeats the purpose of this OOP language, but that would be a distinct implementation.它完全违背了这种 OOP 语言的目的,但这将是一个独特的实现。

It would fall into behavioral patterns for sure, but I guess it would be close to a Strategy or Plugin, given it's about delegating to classes incarnating the function.它肯定会落入行为模式,但我想它会接近策略或插件,因为它是关于委托给体现该功能的类。

BTW, that's pretty much what DynamicProxy is trying to do;顺便说一句,这几乎就是 DynamicProxy 想要做的事情; proxy the interface without any impl class and delegate to a handler which figures a way to respon to the requested method.在没有任何 impl 类的情况下代理接口并委托给一个处理程序,该处理程序提供了一种响应所请求方法的方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM