讲解设计模式的文章特别的多在此不作介绍,我个人总结对设计模式的一些简单理解
如何为你的产品中添加设计模式
单例模式
单例模式有以下的特点:
.. 单例类只可有一个实例。
.. 单例类必须自己创建自己这惟一的实例。
.. 单例类必须给所有其他对象提供这一实例。
单例模式可以应用在应用中只允许一个实例的情况,我现在做的C/S软件中的获取数据库的Connection就要以应用到其中,因为在业务层中连接数据库可能有2次以上,如果将单例模式概念应用到其中,想必效果很棒不管怎么复杂的业务只有一次的连接。
在写方法时如果返回有多个参数请在最后加s表示(这是规范性的问题)
package thtf.ebuilder.db;
import java.io.Serializable;
import javax.sql.DataSource;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
* Spring工具类,通过它获得Spring中的对象
*
* @author 杨伦亮 10:44:21 AM
*/
public class SpringPlugin implements Serializable {
static org.springframework.context.ApplicationContext context = null;
private static class ApplicationContextUtil {
static final SpringPlugin SPRINGPLUGIN = new SpringPlugin();
}
/**
* private的构造函数用于避免外界直接使用new来实例化对象
*/
private SpringPlugin() {
}
public static SpringPlugin getInstance() {
return ApplicationContextUtil.SPRINGPLUGIN;
}
public Object getBean(String beanName) {
if (context == null) {
context = new ClassPathXmlApplicationContext("application*.xml");
}
return context.getBean(beanName);
}
/**
* readResolve方法应对单例对象被序列化时候
*/
private Object readResolve() {
return getInstance();
}
public static void main(String[] args) {
DataSource dataSource = (DataSource) new SpringPlugin()
.getBean("dataSource");
dataSource = (DataSource) new SpringPlugin().getBean("dataSource");
try {
System.out.println("oo" + dataSource.getConnection().isClosed());
} catch (Exception e) {
e.printStackTrace();
}
dataSource = (DataSource) new SpringPlugin().getBean("dataSource");
try {
System.out.println("oo" + dataSource.getConnection().isClosed());
} catch (Exception e) {
e.printStackTrace();
}
}
}