单例模式:
class A {
private static A uniqueInstance=null;
private A(){
}
public static A getInstance(){
if (uniqueInstance == null) {
uniqueInstance = new A();
}
return uniqueInstance;
}
}
主要优点:
1、提供了对唯一实例的受控访问。
2、由于在系统内存中只存在一个对象,因此可以节约系统资源,
对于一些需要频繁创建和销毁的对象单例模式无疑可以提高系统的性能。
3、允许可变数目的实例。
主要缺点:
1、由于单利模式中没有抽象层,因此单例类的扩展有很大的困难。
2、单例类的职责过重,在一定程度上违背了“单一职责原则”。
3、滥用单例将带来一些负面问题,如为了节省资源将数据库连接池对象设计为的单例类,
可能会导致共享连接池对象的程序过多而出现连接池溢出;如果实例化的对象长时间不被利用,
系统会认为是垃圾而被回收,这将导致对象状态的丢失。
这么说吧,有些东西单例是很自然的。比如说现在为太阳系设计一个系统。有个接口 叫 Planet(星球),有一个实现类叫Earth表示地球,地球只有一个,怎么办,用单例。这是从面相对象实践上说的。单纯从编程的角度出发,单例可以节省不必要的内存开销,屏蔽对象创建的复杂性,如果你知道spring并且知道bean默认是单例的,也许会有点感觉,为什么要这样
工厂模式:
//自定义接口
public interface Action {
public void doingAction();
}
//两个实现类
class ZhangSan implements Action{
public void doingAction() {
System.out.println("张三做小动作");
}
}
class LiSi implements Action{
public void doingAction() {
System.out.println("李四做小动作");
}
}
//工厂处理类
public class ActionFactory {
public Action produced(String name){
if("张三".equals(name)){
return new ZhangSan();
}else if("李四".equals(name)){
return new LiSi();
}else {
System.out.println("请输入正确人名");
return null;
}
}
}
//测试
public class FactoryTest {
/**
* 测试类
*/
public static void main(String[] args) {
ActionFactory factory = new ActionFactory();
Action action=factory.produced("李四");
action.doingAction();
}
}
适配器模式:
public void method1() {
System.out.println("this is original method!");
}
}
/* 与原类中的方法相同 */
public void method1();
/* 新类的方法 */
public void method2();
}
public void method2() {
System.out.println("this is the targetable method!");
}
}
public class AdapterTest {
/**
* 测试类
*/
public static void main(String[] args) {
Targetable target = new Adapter();
target.method1();
target.method2();
}
}