一、简单工厂模式
1.定义:专门定义一个类来负责创建其他类的实例,被创建的实例通常都具有共同的父类或接口。
2.意图:提供一个类,由它负责根据一定的条件创建某一具体类的实例。
public class FactoryDemo {
public static void main(String[] args) {
IFruit fruit = Factory.getFruit("苹果");
if (null != fruit) {
System.out.println(fruit.get());
} else {
System.out.println("Sorry");
}
}
}
interface IFruit {
public abstract String get();
}
class Apple implements IFruit {
@Override
public String get() {
return "摘苹果";
}
}
class Orange implements IFruit {
@Override
public String get() {
return "摘橘子";
}
}
class Factory {
public static IFruit getFruit(String name) {
if (name.equals("苹果")) {
return new Apple();
} else if(name.equals("橘子")) {
return new Orange();
} else {
return null;
}
}
}
这个实例的弊端有以下几点:
(1)首次客户端要什么水果,必须要知道这个工厂总共提供哪些水果,否则不知道的话,有可能返回空对象。
(2)如要再扩展一个类,比如:梨子。去实现这个接口,那么工厂这个类就要改代码,这样就违反开闭原则。一旦一个类被使用了,扩展的时候就不能修改了(即对修改是封闭的,对扩展是开放的)
(3)解决办法:用抽象工厂或者工厂方法。
二、策略模式
1.定义:是对算法的包装,把使用算法的责任和算法本身分割开,委派给不同的对象管理。策略模式通常把一系列的算法包装到一系列的策略类里面,作为一个抽象策略类型的子类型。就是:准备一组算法,并将每一个算法封装起来,使得它们可以互换。
2.意图:针对一组算法,将每一个算法封装到具有共同接口的独立的类中,从而使得它们可以互相替换。策略模式使得算法可以在不影响到客户端的情况下发生变化。
public class StrategyDemo {
public static void main(String[] args) {
int[] array = {1,22,56,44,25,11,66,90,83};
BubbleSort bubbleSort = new BubbleSort();
Context context = new Context(bubbleSort);
context.sort(array);
context.printArray(array);
}
}
/**
* 实用策略类
*/
class Context {
ISort iSort = null;
public Context(ISort iSort) {
this.iSort = iSort;
}
/**
* 交给具体接收到的策略类对象来排序
*/
public void sort (int[] array) {
iSort.sort(array);
}
/**
* 输出结果
*/
public void printArray(int[] array) {
for (int i : array) {
System.out.print(i + " ");
}
}
}
interface ISort {
public void sort(int[] array);
}
/**
* 具体的策略类(封装了冒泡排序法)
*/
class BubbleSort implements ISort {
@Override
public void sort(int[] array) {
System.out.println("冒泡排序法");
for (int i = 0; i < array.length - 1; i++) {
for (int j = 0; j < array.length - 1 - i; j++) {
if (array[j] > array[j + 1]) {
int temp = array[j];
array[j] = array[j + 1];
array[j + 1] = temp;
}
}
}
}
}
/**
* 具体的策略类(封装了选择排序法)
*/
class SelectSort implements ISort {
@Override
public void sort(int[] array) {
System.out.println("选择排序法");
int min = 0;
for (int i = 0; i < array.length; i++) {
min = i;
for (int j = i + 1; j < array.length; j++) {
if (array[min] > array[j]) {
min = j;
}
}
if (i != min) {
int temp = array[i];
array[i] = array[min];
array[min] = temp;
}
}
}
}