Web01 初始化 服务 销毁 单例模式。

init: 初始化,创建对象时
service: 服务核心方法,用来接收请求
destroy: 销毁对象

@Override
public void init(ServletConfig arg0) throws ServletException {
	System.out.println("Servlet被创建了");
}

@Override
public void service(ServletRequest arg0, ServletResponse arg1) throws ServletException, IOException {
	System.out.println("服务器收到请求了");
	arg1.getWriter().write(new Date().toString());
}

@Override
public void destroy() {
	System.out.println("Servlet被销毁了");
}

单例模式

–懒汉模式和恶汉模式

public class Singleton {
// 属性
int a;
// 方法
// 类加载时,对象就已经创建好 - 饿汉模式
//	private static Singleton single = new Singleton();
//	public static Singleton print() {
//		return single;
//	}
// 使用对象时,再创建对象 - 懒汉模式
private static Singleton single = null;
public static Singleton print() {
	//锁住,不然线程执行到if语句归还时间片就会产生错误。
	synchronized (single) {
		if (single == null) {
			single = new Singleton();
		}
	}
	return single;
}

// 1.不能直接new,私有化构造器
private Singleton() {
	
}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值