工厂方法模式原理是在父类提供一个创建对象的方法,允许子类决定实例化对象的类型。
注意,并不一定每次调用工厂方法都会创建新的实例。工厂方法也可以返回缓存,对象池或其他的已有对象。
buttons/Button.java:通用的产品接口
public interface Button{
void render();
void onClick();
}
HtmlButton.java:具体产品
public class HtmlButton implements Button{
public void render(){
System.out.println("<button>Test Button</button");
onClick();
}
}
public void onClick(){
System.out.println("Click !Button says-'Hellow world'");
}
windowsbutton.java:另一个具体产品
public class WindowsButton implements Button {
JPanel panel = new JPanel();
JFrame frame = new JFrame();
JButton button;
public void render() {
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel label = new JLabel("Hello World!");
label.setOpaque(true);
label.setBackground(new Color(235, 233, 126));
label.setFont(new Font("Dialog", Font.BOLD, 44));
label.setHorizontalAlignment(SwingConstants.CENTER);
panel.setLayout(new FlowLayout(FlowLayout.CENTER));
frame.getContentPane().add(panel);
panel.add(label);
onClick();
panel.add(button);
frame.setSize(320, 200);
frame.setVisible(true);
onClick();
}
public void onClick() {
button = new JButton("Exit");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
frame.setVisible(false);
System.exit(0);
}
});
}
}
HtmlDialog.java:具体创建者
public class HtmlDialog extends Dialog {
@Override
public Button createButton() {
return new HtmlButton();
}
}
WindowDialog.java:另一个具体创建者
public class WindowsDialog extends Dialog {
@Override
public Button createButton() {
return new WindowsButton();
}
}
public class Demo {
private static Dialog dialog;
public static void main(String[] args) {
configure();
runBusinessLogic();
}
/**
* The concrete factory is usually chosen depending on configuration or
* environment options.
*/
static void configure() {
if (System.getProperty("os.name").equals("Windows 10")) {
dialog = new WindowsDialog();
} else {
dialog = new HtmlDialog();
}
}
/**
* All of the client code should work with factories and products through
* abstract interfaces. This way it does not care which factory it works
* with and what kind of product it returns.
*/
static void runBusinessLogic() {
dialog.renderWindow();
}
}
客户端不需要关注对象是谁创建的,只要通过工厂中静态方法就可以直接获取其需要的对象。
,使用工厂对象创建具体的产品对象,从而使得对象的使用和创建过程进行的分离。
客户端不需要关注对象是谁创建的,只要通过工厂中静态方法就可以直接获取其需要的对象。
版权说明 : 本文为转载文章, 版权归原作者所有 版权申明
原文链接 : https://blog.csdn.net/weixin_44932487/article/details/113918658
内容来源于网络,如有侵权,请联系作者删除!