// Button.java
public interface Button {
void render();
void onClick();
}
// HtmlButton.java
public class HtmlButton implements Button {
@Override
public void render() {
System.out.println("Html按钮渲染");
onClick();
}
@Override
public void onClick() {
System.out.println("点击Html按钮");
}
}
// WindowsButton.java
public class WindowsButton implements Button {
@Override
public void render() {
System.out.println("Windows按钮渲染");
onClick();
}
@Override
public void onClick() {
System.out.println("点击Windows按钮");
}
}
// Dialog.java
public abstract class Dialog {
public void renderWindow() {
Button okButton = createButton();
okButton.render();
}
public abstract Button createButton();
}
// HtmlDialog.java
public class HtmlDialog extends Dialog {
@Override
public Button createButton() {
return new HtmlButton();
}
}
// WindowsDialog.java
public class WindowsDialog extends Dialog {
@Override
public Button createButton() {
return new WindowsButton();
}
}
// Demo.java
public class Demo {
private static Dialog dialog;
public static void main(String[] args) {
configure();
runBusinessLogic();
}
static void configure() {
if (System.getProperty("os.name").equals("Windows 10")) {
dialog = new WindowsDialog();
} else {
dialog = new HtmlDialog();
}
}
static void runBusinessLogic() {
dialog.renderWindow();
}
}