- 单例模式
即这种模式只会生成一个对象,我们知道java通过new 方法生成对象,这意味着每new一个就会生成一个对象,哪怎么样才能让一个类只生成一个实例呢?
public class SingletonTest{
public static void main(String[] args) {
/**
* Earth earth1 = new Earth();
* 这种方法生成对象会出错,
* 因为Earth中构造方法的访问权限为private,
* 即外部无法访问。
*/
Earth earth1 = Earth.getEarth();
Earth earth2 = Earth.getEarth();
//打印一下看看是否相同
System.out.println(earth1==earth2);
}
}
/**
* 我们知道只有一个地球,因此这个类只会生成一个实例。
*
*/
class Earth{
//private访问修饰符使得其他类无法访问
private static Earth earth = new Earth();
//私有的构造方法
private Earth() {
}
//返回实例对象的方法
public static Earth getEarth() {
return earth;
}
}
结果为:
true
- 策略模式:
策略模式是一种较为简单的模式,分为三部分:
- 环境角色:环境角色中持有一个关于策略角色的引用,根据传入的不同策略,执行不同的操作。
- 抽象策略角色:一个通用的接口,只是定义需要做什么操作,并不做具体操作。
具体策略角色:一个实现了抽象策略角色的类,提供具体的执行步骤。
比如在TreeSet中放入一些User类的实例,那么就需要提供一个关于确定Person对象唯一性的方法。比如按照姓名,还是id来,这就是策略。
举一个加减乘除的例子:
抽象策略角色
public interface Strategy {
public int compute(int a,int b);
}
具体策略角色
class Sum implements Strategy{
@Override
public int compute(int a, int b) {
return a+b;
}
}
class Subtract implements Strategy{
@Override
public int compute(int a, int b) {
return a-b;
}
}
class Multiply implements Strategy{
@Override
public int compute(int a, int b) {
return a*b;
}
}
class Divide implements Strategy{
@Override
public int compute(int a, int b) {
return a/b;
}
}
环境角色:
public class Environment {
/*
* 环境角色持有对策略角色的一个应用,这里主要是用到了多态,
* 父类引用可以指向子类对象。
*/
private Strategy strategy;
public Environment(Strategy strategy) {
this.strategy = strategy;
}
public void setEnvironment(Strategy strategy) {
this.strategy = strategy;
}
public int compute(int a,int b) {
return this.strategy.compute(a, b);
}
public static void main(String[] args) {
/*
* 通过传入不同策略,执行不同的运算
*/
Environment env = new Environment(new Sum());
int result = env.compute(3, 4);
System.out.println(result);
env.setEnvironment(new Multiply());
int result2 = env.compute(3, 4);
System.out.println(result2);
}
}
运行结果为:
7
12