如何在多通道对象处理场景下用Java遵循单一职责原则?
Great question! Let's break this down using the Single Responsibility Principle (SRP), which states that an interface (or class) should have only one reason to change. Your original ATaskProcessor interface violates SRP because it’s trying to handle three completely separate responsibilities: processing objects from Channel A, Channel B, and Channel C. Any tweak to one channel’s logic would force changes to the entire interface and all its implementations—this gets messy fast.
Here's how to fix it, step by step:
1. Start with a Shared Base Interface
Since all channels share a common save method, create a base interface that encapsulates this universal responsibility:
public interface ChannelProcessor { // Universal save method for all channels void save(Object channelObject); }
2. Split into Channel-Specific Interfaces
Create a dedicated interface for each channel, extending the base interface. Each interface will only contain processing methods for its own channel’s objects:
For Channel A:
public interface AChannelProcessor extends ChannelProcessor { void a1Process(Arguments args); void a2Process(Arguments args); void a3Process(Arguments args); }
For Channel B:
public interface BChannelProcessor extends ChannelProcessor { void b1Process(Arguments args); void b2Process(Arguments args); void b3Process(Arguments args); }
For Channel C:
public interface CChannelProcessor extends ChannelProcessor { void c1Process(Arguments args); void c2Process(Arguments args); void c3Process(Arguments args); }
3. Implement Channel-Specific Processors
Now you can create separate implementation classes for each channel. For example:
public class AChannelProcessorImpl implements AChannelProcessor { @Override public void save(Object channelObject) { // Implementation for saving A-channel objects } @Override public void a1Process(Arguments args) { // Logic specific to processing A1 } // Implement a2Process and a3Process here }
Why This Works
- Clearer Responsibility: Each interface now only handles logic for one channel. If Channel A needs a new
a4Processmethod, onlyAChannelProcessorand its implementations need to change—no impact on B or C channels. - Easier Maintenance: Code for each channel is isolated, so debugging or updating one set of logic doesn’t risk breaking unrelated code.
- Better SRP Adherence: Each interface has exactly one reason to change: modifications to its associated channel’s processing requirements.
If you ever find that even a single channel’s object processing has distinct, unrelated responsibilities (e.g., A1 handles payment logic while A2 handles user validation), you could split those into even smaller interfaces—but for your current setup, channel-specific interfaces are the perfect balance.
内容的提问来源于stack exchange,提问作者Mohamed Said Benmousa

