Middle
Can you give an example of using the 'Factory' design pattern in the Android framework?
sobes.tech AI
Answer from AI
// Abstract class or interface for the product
interface TextView {
void setText(String text);
void setTextColor(int color);
}
// Concrete class for standard TextView
class StandardTextView implements TextView {
android.widget.TextView internalTextView;
StandardTextView(android.content.Context context) {
internalTextView = new android.widget.TextView(context);
}
@Override
public void setText(String text) {
internalTextView.setText(text);
}
@Override
public void setTextColor(int color) {
internalTextView.setTextColor(color);
}
}
// Concrete class for Bold TextView
class BoldTextView implements TextView {
android.widget.TextView internalTextView;
BoldTextView(android.content.Context context) {
internalTextView = new android.widget.TextView(context);
internalTextView.setTypeface(null, android.graphics.Typeface.BOLD);
}
@Override
public void setText(String text) {
internalTextView.setText(text);
}
@Override
public void setTextColor(int color) {
internalTextView.setTextColor(color);
}
}
// Abstract factory class
abstract class TextViewFactory {
abstract TextView createTextView(android.content.Context context);
}
// Concrete factory for standard TextView
class StandardTextViewFactory extends TextViewFactory {
@Override
TextView createTextView(android.content.Context context) {
return new StandardTextView(context);
}
}
// Concrete factory for Bold TextView
class BoldTextViewFactory extends TextViewFactory {
@Override
TextView createTextView(android.content.Context context) {
return new BoldTextView(context);
}
}
// Example usage in Activity
class MyActivity extends androidx.appcompat.app.AppCompatActivity {
@Override
protected void onCreate(android.os.Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// ...
TextViewFactory standardFactory = new StandardTextViewFactory();
TextView standardTextView = standardFactory.createTextView(this);
standardTextView.setText("Hello, world!");
TextViewFactory boldFactory = new BoldTextViewFactory();
TextView boldTextView = boldFactory.createTextView(this);
boldTextView.setText("Bold text");
// Adding to layout
android.widget.LinearLayout linearLayout = new android.widget.LinearLayout(this);
linearLayout.setOrientation(android.widget.LinearLayout.VERTICAL);
linearLayout.addView(((StandardTextView) standardTextView).internalTextView);
linearLayout.addView(((BoldTextView) boldTextView).internalTextView);
setContentView(linearLayout);
}
}