Reputation: 125
In my UI project, I have few screens that share the same header style only the text is specific to the screens. What will be a good way to implement this?
or
Hope it make sense..
Upvotes: 2
Views: 281
Reputation: 11805
My question is does the subclasses have any useful functionality? If not, why wouldn't you just have the one concrete class and pass it some sort of data container to populate the fields?
If there's no behavioral differences, you'd be much better served just passing data and/or collaborators into either the constructor, or via property setters.
Upvotes: 0
Reputation: 20323
You can change your option 1 slightly
public abstract class SuperUI {
private HeaderComponenet headerComponent;//have getter setter
}
public class BaseUI extends SuperUI{
private void changeHeaderComponent(){
headerComponent.setText("Changed");
}
}
public class HeaderComponent extends JComponent{
public HeaderComponent(){
//create the default header here
}
}
In this case if the default header component has to be changed you don't have to change your SuperUI, as you have separated the header from SuperUI, you can do the same for footer component if need be.
Upvotes: 0
Reputation: 9206
"Have abstract method in super class to create the components, sub class will implement these methods to create the component."
In my opinion this solution is easier to maintain.
Upvotes: 0
Reputation: 33534
When the behaviour Keeps changing...encapsulate it in either abstact class or interface.
Its better to have an
Abstract class, with the non-abstract method to create the Header,
and an Abstract method to create the text
..In the sub class u can create the text of your choice by implementing the abstract method.
Upvotes: 0
Reputation: 2482
The second option is more viable.
Remember: Single Responsibility Principle
Both options work but the second one will go a longer way to reduce coupling in your code.
Upvotes: 0
Reputation: 29654
Do you really need an abstract class?
public class UIScreen {
public UIScreen(String headerText) {
//set everything up here w/ the right text
}
}
// elsewhere ....
UIScreen mainScreen = new UIScreen("Main Screen");
Upvotes: 3
Reputation: 36446
Depends on whether you want the super class able to be instantiated or not. It's like having an Animal
super class and Dog
and Cat
subclasses. Do you want people to be able to create a generic Animal
?
If so, it should be a normal class. If not, it should be declared abstract
.
So ultimately the question is: Is there a default behavior? If not, then make it abstract.
Upvotes: 0
Reputation: 18488
Create the abstract class with the generic header method, and define one method for all the subclasses to implement would be best.
Upvotes: 0