面向可复用性
Adapter 适配器模式
添加适配器,使得原配件能复用。适配器实现新接口,以继承或复用形式适配旧配件。
实现代码:
public interface Itarget {
public void greet();
}
public class Adaptee {
public void smile() {
System.out.println("Adaptee: smile");
}
}
public class Adapter implements Itarget {
private Adaptee api;
public Adapter() {
api = new Adaptee();
}
@Override
public void greet() {
api.smile();
}
}
public class Client {
public static void main(String[] args) {
Itarget it = new Adapter();
it.greet();
}
}
Decorator 装饰器模式
装饰器是个抽象类,实现组件接口,并在内部与一个组件关联。具体组件、具体装饰器分别实现接口、继承装饰器。
public interface Product {
public void show();
}
public class Icecream implements Product{
@Override
public void show() {
System.out.println("icecream");
}
}
public abstract class Decorator implements Product {
Product ice = null;
public Decorator(Product ice) {
this.ice = ice;
}
}
public class RedDecorator extends Decorator{
public RedDecorator(Product ice) {
super(ice);
}
@Override
public void show() {
System.out.println("red");
ice.show();
}
}
public class SweetDecorator extends Decorator{
public SweetDecorator(Product ice) {
super(ice);
}
@Override
public void show() {
System.out.println("sweet");
ice.show();
}
}
public class Client {
public static void main(String[] args) {
Product p = new SweetDecorator(new RedDecorator(new Icecream()));
p.show();
}
}
façade 外观模式
外观模式是给用户提供简单接口,实现时调用内部一系列方法处理事物,相当于给客户提供便捷的窗口服务
Strategy 策略模式
策略模式是提供策略接口,由具体类实现。其他类调用接口的方法用某种策略解决问题。
public interface Strategy {
public int times(int a,int b);
}
public class StrategyA implements Strategy{
@Override
public int times(int a, int b) {
return a*b;
}
}
public class StrategyB implements Strategy {
@Override
public int times(int a, int b) {
int s=0;
while(b>0) {
b--;
s+=a;
}
return s;
}
}
public class Content {
public int times(int a,int b,Strategy S) {
return S.times(a, b);
}
public static void main(String[] args) {
Content C = new Content();
int a=C.times(3, 4, new StrategyA());
int b=C.times(3, 4, new StrategyB());
System.out.println(a+" "+b);
}
}
Template 模板模式
模板模式是指做事有一系列步骤,在模板中安排好步骤的顺序,具体类实现各步骤
public abstract class Template {
public abstract void map();
public abstract void reduce();
public void work() {
map();
reduce();
}
}
public class ImplementA extends Template{
public void map() {
System.out.println("map");
}
public void reduce() {
System.out.println("reduce");
}
}
public class Client {
public static void main(String[] args) {
Template t = new ImplementA();
t.work();
}
}
Iterator 迭代模式
提供迭代器,被迭代对象是Iterable的,迭代器为Iterator类型,实现next、hasNext方法
public class MyArray implements Iterable<Integer>{
int a[];
public MyArray() {
a=new int[]{3,7,9,5,4};
}
public Iterator<Integer> iterator(){
return new Iterator<Integer>() { //匿名内部类
int cur=0;
@Override
public boolean hasNext() {
return cur<a.length;
}
@Override
public Integer next() {
return a[cur++];
}
};
}
public static void main(String[] args) {
MyArray my = new MyArray();
for(int x:my) {
System.out.println(x);
}
}
}