单例模式应用之聊天界面

来源:互联网 发布:淘宝禁售商品管理规范 编辑:程序博客网 时间:2024/05/27 14:15

单例模式:

定义:单例模式,是一种常用的软件设计模式。在它的核心结构中只包含一个被称为单例的特殊类。通过单例模式可以保证系统中一个类只有一个实例。即一个类只有一个对象实例

要点有三:一是某个类必须只能有一个实例;而是它必须自行创建这个实例;三是它必须自行向整个系统提供这个实例。

单例模式的结构图如下:

在单例模式实现过程中,需要注意以下三点:

(1)单例类的构造函数为私有的。

(2)提供一个自身的静态私有成员变量。

(3)提供一个公有的静态工厂方法。


用到单例模式的地方很多,举几个例子,QQ的聊天框,与每位好友只能打开一个聊天框,Windows任务管理器,word中的搜索框等等。

下面是一个基于单例模式实现的聊天框,点击主界面按钮就会弹出聊天框,再次点击就会隐藏它。


主窗口:

package com.sin;import java.awt.*;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import javax.swing.*;public class MainFrame extends JFrame implements ActionListener{JButton button1;JLabel label;public MainFrame(int width,int height){button1 = new JButton("button1");button1.addActionListener(this);button1.setPreferredSize(new Dimension(20, 40));label = new JLabel("我是父窗口",JLabel.CENTER);Container c = this.getContentPane();c.add(button1,BorderLayout.SOUTH);c.add(label,BorderLayout.NORTH);//setLocation(200,300);setLocationRelativeTo(null);setSize(width,height);setVisible(true);setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);}public static void main(String[] args) {new MainFrame(400,300);}@Overridepublic void actionPerformed(ActionEvent e) {if(e.getSource() == button1){if(ChatFrame.getInstance().isVisible())ChatFrame.getInstance().hide();elseChatFrame.getInstance().show();}}}


聊天框:

package com.sin;import java.awt.*;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.awt.event.KeyAdapter;import java.awt.event.KeyEvent;import java.awt.event.KeyListener;import java.awt.event.WindowAdapter;import java.awt.event.WindowEvent;import javax.swing.*;public class ChatFrame extends JFrame{JTextField text;JTextArea area;JButton btn;private static ChatFrame chat = null;//单例private ChatFrame() {//私有构造函数JPanel panel = new JPanel();JLabel label = new JLabel("消息");area = new JTextArea(15,30);btn = new JButton("发送");btn.addActionListener(new MyActionListener());text = new JTextField(20);text.addKeyListener(new KeyAdapter() {//监听键盘事件public void keyPressed(KeyEvent e){if(e.getKeyChar()==KeyEvent.VK_ENTER) {//按回车键执行相应操作; area.append("我说:"+text.getText()+"\n");text.setText("");}}});JScrollPane jsp = new JScrollPane(area);panel.add(label);panel.add(text);panel.add(btn);this.addWindowListener( new WindowAdapter() {    public void windowOpened( WindowEvent e ){        text.requestFocus();    }}); this.setTitle("聊天框");this.setLayout(new BorderLayout());this.add(panel,BorderLayout.SOUTH);this.add(area,BorderLayout.CENTER);this.setLocation(200, 300);this.setSize(400,300);this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);this.setVisible(true);}class MyActionListener implements ActionListener{//实现按钮事件监听@Overridepublic void actionPerformed(ActionEvent e) {if(e.getSource() == btn) {area.append("我说:"+text.getText()+"\n");text.setText("");}}}public static ChatFrame getInstance() {//静态工厂方法if(chat==null)chat = new ChatFrame();return chat;}}



原创粉丝点击