1.设计模式的原则:
- 单一职责原则:一个类只做它该做的事情
- 开闭原则:软件实体应当对扩展开放,对修改关闭
- 依赖倒转原则:面向接口编程
- 里氏替换原则:任何时候都可以用子类型替换掉父类型
- 接口隔离原则:接口要小而专,绝不能大而全
- 合成聚合复用原则:优先使用聚合或合成关系复用代码
- 迪米特法则:一个对象应当对其他对象有尽可能少的了解(低耦合)
2.工厂模式代码
package shejimoshi;
public class Factory {
public static void main(String[] args) {
//工厂模式
carFactory bwm = new bmwFactory();
Car car = bwm.create();
car.run();
carFactory benz=new benzFactory();
Car car1 = benz.create();
car1.run();
}
}
//定义车的接口
interface Car {
void run();
}
class Bmw implements Car {
@Override
public void run() {
System.out.println("bmw---run");
}
}
class Benz implements Car {
@Override
public void run() {
System.out.println("Benz--run");
}
}
//生产车的工厂抽象类
abstract class carFactory {
public abstract Car create();
}
class bmwFactory extends carFactory {
@Override
public Car create() {
return new Bmw();
}
}
class benzFactory extends carFactory{
@Override
public Car create() {
return new Benz();
}
}
3.单例模式
//懒汉式---用到实例再创建
public class Singleton {
private static Singleton instance;
private Singleton() {
}
private static synchronized Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}
//饿汉式---初始化即创建
public class Singleton1 {
private static Singleton1 instance = new Singleton1();
private Singleton1() {
}
private static Singleton1 getInstance() {
return instance;
}
}
//双重校验锁
public class Singleton2 {
private volatile static Singleton2 instance;
private Singleton2() {
}
private static Singleton2 getInstance() {
if (instance == null) {
synchronized (Singleton2.class) {
if (instance == null) {
instance = new Singleton2();
}
}
}
return instance;
}
}