java - How to design a class in this case? Are there any design patterns?
曾经蜡笔没有小新
曾经蜡笔没有小新 2017-06-17 09:15:50
0
5
892

A kind of data passing through hardware devices uses a special format. The first paragraph is the id, and the latter paragraph is the data.

The previous paragraph represents which type of data it is, such as A, B, C, etc.

According to the previous type, we take some of the following digits. For example, for type A, we need the 1-3 digits of the data, and for type B, we need the 20th and 22nd digits.

When designing now, we only need to be able to accept categories a and b, but in the future we want to accept category c, category d, etc., and the operations on the data are also different. For example, category a needs to accept 1-3 digits. All are multiplied by two, the twentieth digit of type b is added by 1, and the twenty-second digit remains unchanged z

The question is how should it be designed to facilitate future expansion? For example, I want to support class d without rewriting the code....

曾经蜡笔没有小新
曾经蜡笔没有小新

reply all(5)
三叔

If it’s complicated, use the strategy pattern. If it’s not complicated, use direct OO inheritance. Different types of messages are handled by different subclasses.

某草草

The data protocol format should be well defined: for example: the high 3 digits represent the type, the middle 2 digits represent the protocol version, and the last digits represent the data.
After the protocol is stipulated, it is processed through the template method, and the specific analysis is placed in the subclass, and the general analysis is placed in the parent class.
In this way, when expanding, you don’t need to change the original code, you only need to write a new implementation.

伊谢尔伦

There is no need to use design patterns at all, traditional inheritance is enough, and each subclass can take different fields.

大家讲道理

If you must use design pattern, you can consider Strategy pattern

三叔

You also need to judge the subsequent users. Factory mode, strategy mode, and agent mode may all meet your expansion needs. In fact, the important thing is the idea. Design according to the six principles. There is no need to stick to a certain mode. According to the needs , the code slowly evolves, and in the end it may naturally conform to a certain pattern, or it may be a combination of multiple patterns.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template