顺口溜
公公原简单
小乔组装是外带
明泽姐弟中观被木房装册
命责解迭中观备模访状策
礼仪开合接地线
创建型模式-- > 对象怎么来
结构型模式-- > 对象和谁有关
行为型模式-- > 对象与对象在干嘛
J2EE 模式-- > 对象合起来要干嘛
设计模式的六大原则
1 、开闭原则(Open Close Principle)对扩展开放,对修改关闭。
2 、里氏代换原则(Liskov Substitution Principle) 任何基类可以出现的地方,子类一定可以出现
3 、依赖倒转原则(Dependence Inversion Principle)真对接口编程,依赖于抽象而不依赖于具体
4 、接口隔离原则(Interface Segregation Principle)使用多个隔离的接口,比使用单个接口要好。降低依赖,降低耦合。
5 、迪米特法则(最少知道原则)(Demeter Principle)一个实体应当尽量少的与其他实体之间发生相互作用,使得系统功能模块相对独立。
6 、合成复用原则(Composite Reuse Principle)原则是尽量使用合成/ 聚合的方式,而不是使用继承。
创建型
抽象工厂模式 http:
工厂方法 http:
建造者模式 http:
原型模式 http:
单态模式 http:
结构型
适配器模式 http:
桥接模式 http:
组合模式 http:
外观模式 http:
装饰者模式 http:
享元模式 http:
代理模式 http:
行为型
责任链模式 http:
命令模式 http:
解释器模式 http:
迭代模式 http:
中介者模式 http:
备忘录模式 http:
观察者模式 http:
状态模式 http:
策略模式 http:
模板方法模式 http:
访问者模式 http:
适配器模式 装饰模式 类的适配器模式 桥接模式 代理模式 对象的适配器模式 组合模式 外观模式 接口的适配器模式 享元模式
父子关系 兄弟关系 状态 中间类 策略模式 观察者模式 备忘录模式 访问者模式 模板方法模式 迭代子模式 状态模式 中介者模式 责任链模式 解释权模式 命令模式
~~ ~~
对象怎么来
结构型模式–>对象和谁有关
行为型模式–>对象与对象在干嘛
工厂方法
public interface Color {
void fill ( ) ;
}
-- -- -- -- -- -- -- -- -- -- -
public class Blue implements Color {
@Override
public void fill ( ) {
System. out. println ( "Inside Blue:fill() method." ) ;
}
}
public class Green implements Color {
@Override
public void fill ( ) {
System. out. println ( "Inside Green :fill() method." ) ;
}
}
public class Red implements Color {
@Override
public void fill ( ) {
System. out. println ( "Inside Red:fill() method." ) ;
}
}
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -
public interface Shape {
void draw ( ) ;
}
public class Circle implements Shape {
@Override
public void draw ( ) {
System. out. println ( "Inside Square:draw() method." ) ;
}
}
public class Square implements Shape {
@Override
public void draw ( ) {
System. out. println ( "Inside Square:draw() method." ) ;
}
}
public class Rectangle implements Shape {
@Override
public void draw ( ) {
System. out. println ( "Inside Rectangle:draw() method." ) ;
}
}
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -
public abstract class AbstractFactory {
abstract Color getColor ( String color) ;
abstract Shape getShape ( String shape) ;
}
public class ShapeFactory extends AbstractFactory {
@Override
Color getColor ( String color) {
return null;
}
@Override
Shape getShape ( String shapeType) {
if ( shapeType == null) {
return null;
}
if ( shapeType. equalsIgnoreCase ( "CIRCLE" ) ) {
return new Circle ( ) ;
} else if ( shapeType. equalsIgnoreCase ( "RECTANGLE" ) ) {
return new Rectangle ( ) ;
} else if ( shapeType. equalsIgnoreCase ( "SQUARE" ) ) {
return new Square ( ) ;
}
return null;
}
}
public class ColorFactory extends AbstractFactory {
@Override
Color getColor ( String color) {
if ( color == null) {
return null;
}
if ( color. equalsIgnoreCase ( "RED" ) ) {
return new Red ( ) ;
} else if ( color. equalsIgnoreCase ( "GREEN" ) ) {
return new Green ( ) ;
} else if ( color. equalsIgnoreCase ( "BLUE" ) ) {
return new Blue ( ) ;
}
return null;
}
@Override
Shape getShape ( String shape) {
return null;
}
}
public class FactoryProducer {
public static AbstractFactory getFactory ( String choice) {
if ( choice. equalsIgnoreCase ( "SHAPE" ) ) {
return new ShapeFactory ( ) ;
} else if ( choice. equalsIgnoreCase ( "COLOR" ) ) {
return new ColorFactory ( ) ;
}
return null;
}
}
package com. creational. abstract_Factory;
public class AbstractFactoryPatternDemo {
public static void main ( String[ ] args) {
AbstractFactory shapeFactory = FactoryProducer. getFactory ( "SHAPE" ) ;
Shape shape1 = shapeFactory. getShape ( "CIRCLE" ) ;
shape1. draw ( ) ;
Shape shape2 = shapeFactory. getShape ( "RECTANGLE" ) ;
shape2. draw ( ) ;
Shape shape3 = shapeFactory. getShape ( "SQUARE" ) ;
shape3. draw ( ) ;
AbstractFactory colorFactory = FactoryProducer. getFactory ( "COLOR" ) ;
Color color1 = colorFactory. getColor ( "RED" ) ;
color1. fill ( ) ;
Color color2 = colorFactory. getColor ( "Green" ) ;
color2. fill ( ) ;
Color color3 = colorFactory. getColor ( "BLUE" ) ;
color3. fill ( ) ;
}
}
抽象工厂
public interface Shape {
void draw ( ) ;
}
public class Circle implements Shape {
@Override
public void draw ( ) {
System. out. println ( "Inside Circle::draw() method." ) ;
}
}
public class Rectangle implements Shape {
@Override
public void draw ( ) {
System. out. println ( "Inside Rectangle::draw() method." ) ;
}
}
public class Square implements Shape {
@Override
public void draw ( ) {
System. out. println ( "Inside Square::draw() method." ) ;
}
}
public class ShapeFactory {
public Shape getShape ( String shapeType) {
if ( shapeType == null) {
return null;
}
if ( shapeType. equalsIgnoreCase ( "CIRCLE" ) ) {
return new Circle ( ) ;
} else if ( shapeType. equalsIgnoreCase ( "RECTANGLE" ) ) {
return new Rectangle ( ) ;
} else if ( shapeType. equalsIgnoreCase ( "SQUARE" ) ) {
return new Square ( ) ;
}
return null;
}
}
原型
重点:浅复制,深复制
浅复制:将一个对象复制后,基本数据类型的变量都会重新创建,
而引用类型,指向的还是原对象所指向的。
深复制:将一个对象复制后,不论是基本数据类型还有引用类型,都是重新创建的。
简单来说,就是深复制进行了完全彻底的复制,而浅复制不彻底。
class SerializableObject implements Serializable {
private String name = "deep clone" ;
}
public class Prototype implements Cloneable , Serializable {
private String string;
private SerializableObject obj;
public Object clone ( ) throws CloneNotSupportedException {
Prototype proto = ( Prototype) super . clone ( ) ;
return proto;
}
public Object deepClone ( ) throws IOException, ClassNotFoundException {
ByteArrayOutputStream bos = new ByteArrayOutputStream ( ) ;
ObjectOutputStream oos = new ObjectOutputStream ( bos) ;
oos. writeObject ( this ) ;
ByteArrayInputStream bis = new ByteArrayInputStream ( bos. toByteArray ( ) ) ;
ObjectInputStream ois = new ObjectInputStream ( bis) ;
return ois. readObject ( ) ;
}
public String getString ( ) {
return string;
}
public void setString ( String string) {
this . string = string;
}
public SerializableObject getObj ( ) {
return obj;
}
public void setObj ( SerializableObject obj) {
this . obj = obj;
}
}
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
原型模式有两种表现形式:(1 )简单形式、(2 )登记形式,这两种表现形式仅仅是原型模式的不同实现。
简单形式
public interface Prototype {
public Object clone ( ) ;
}
public class ConcretePrototype1 implements Prototype {
public Prototype clone ( ) {
Prototype prototype = new ConcretePrototype1 ( ) ;
return prototype;
}
}
public class ConcretePrototype2 implements Prototype {
public Prototype clone ( ) {
Prototype prototype = new ConcretePrototype2 ( ) ;
return prototype;
}
}
public class Client {
private Prototype prototype;
public Client ( Prototype prototype) {
this . prototype = prototype;
}
public void operation ( Prototype example) {
Prototype copyPrototype = prototype. clone ( ) ;
}
}
登记形式
多了一个原型管理器( PrototypeManager) 角色,该角色的作用是:创建具体原型类的对象,并记录每一个被创建的对象。
public interface Prototype {
public Prototype clone ( ) ;
public String getName ( ) ;
public void setName ( String name) ;
}
public class ConcretePrototype1 implements Prototype {
private String name;
public Prototype clone ( ) {
ConcretePrototype1 prototype = new ConcretePrototype1 ( ) ;
prototype. setName ( this . name) ;
return prototype;
}
public String toString ( ) {
return "Now in Prototype1 , name = " + this . name;
}
@Override
public String getName ( ) {
return name;
}
@Override
public void setName ( String name) {
this . name = name;
}
}
public class ConcretePrototype2 implements Prototype {
private String name;
public Prototype clone ( ) {
ConcretePrototype2 prototype = new ConcretePrototype2 ( ) ;
prototype. setName ( this . name) ;
return prototype;
}
public String toString ( ) {
return "Now in Prototype2 , name = " + this . name;
}
@Override
public String getName ( ) {
return name;
}
@Override
public void setName ( String name) {
this . name = name;
}
}
public class PrototypeManager {
private static Map< String, Prototype> map = new HashMap < String, Prototype> ( ) ;
private PrototypeManager ( ) { }
public synchronized static void setPrototype ( String prototypeId , Prototype prototype) {
map. put ( prototypeId, prototype) ;
}
public synchronized static void removePrototype ( String prototypeId) {
map. remove ( prototypeId) ;
}
public synchronized static Prototype getPrototype ( String prototypeId) throws Exception{
Prototype prototype = map. get ( prototypeId) ;
if ( prototype == null) {
throw new Exception ( "您希望获取的原型还没有注册或已被销毁" ) ;
}
return prototype;
}
}
public class Client {
public static void main ( String[ ] args) {
try {
Prototype p1 = new ConcretePrototype1 ( ) ;
PrototypeManager. setPrototype ( "p1" , p1) ;
Prototype p3 = PrototypeManager. getPrototype ( "p1" ) . clone ( ) ;
p3. setName ( "张三" ) ;
System. out. println ( "第一个实例:" + p3) ;
Prototype p2 = new ConcretePrototype2 ( ) ;
PrototypeManager. setPrototype ( "p1" , p2) ;
Prototype p4 = PrototypeManager. getPrototype ( "p1" ) . clone ( ) ;
p4. setName ( "李四" ) ;
System. out. println ( "第二个实例:" + p4) ;
PrototypeManager. removePrototype ( "p1" ) ;
Prototype p5 = PrototypeManager. getPrototype ( "p1" ) . clone ( ) ;
p5. setName ( "王五" ) ;
System. out. println ( "第三个实例:" + p5) ;
} catch ( Exception e) {
e. printStackTrace ( ) ;
}
}
}
clone ( ) 方法将对象复制了一份并返还给调用者。所谓“复制”的含义与clone ( ) 方法是怎么实现的。一般而言,clone ( ) 方法满足以下的描述:
(1 )对任何的对象x,都有:x. clone ( ) != x。换言之,克隆对象与原对象不是同一个对象。
(2 )对任何的对象x,都有:x. clone ( ) . getClass ( ) == x. getClass ( ) ,换言之,克隆对象与原对象的类型一样。
(3 )如果对象x的equals ( ) 方法定义其恰当的话,那么x. clone ( ) . equals ( x) 应当成立的。
建造者
public interface Packing {
public String pack ( ) ;
}
public class Bottle implements Packing {
@Override
public String pack ( ) {
return "Bottle" ;
}
}
public class Wrapper implements Packing {
@Override
public String pack ( ) {
return "Wrapper" ;
}
}
public interface Item {
public String name ( ) ;
public Packing packing ( ) ;
public float price ( ) ;
}
public abstract class Burger implements Item {
@Override
public Packing packing ( ) {
return new Wrapper ( ) ;
}
@Override
public abstract float price ( ) ;
}
public class VegBurger extends Burger {
@Override
public float price ( ) {
return 25.0f ;
}
@Override
public String name ( ) {
return "Veg Burger" ;
}
}
public class ChickenBurger extends Burger {
@Override
public float price ( ) {
return 50.5f ;
}
@Override
public String name ( ) {
return "Chicken Burger" ;
}
}
public abstract class ColdDrink implements Item {
@Override
public Packing packing ( ) {
return new Bottle ( ) ;
}
@Override
public abstract float price ( ) ;
}
public class Coke extends ColdDrink {
@Override
public float price ( ) {
return 30.0f ;
}
@Override
public String name ( ) {
return "Coke" ;
}
}
public class Pepsi extends ColdDrink {
@Override
public float price ( ) {
return 35.0f ;
}
@Override
public String name ( ) {
return "Pepsi" ;
}
}
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -
public class Meal {
private List< Item> items = new ArrayList < Item> ( ) ;
public void addItem ( Item item) {
items. add ( item) ;
}
public float getCost ( ) {
float cost = 0.0f ;
for ( Item item : items) {
cost += item. price ( ) ;
}
return cost;
}
public void showItems ( ) {
for ( Item item : items) {
System. out. print ( "Item : " + item. name ( ) ) ;
System. out. print ( ", Packing : " + item. packing ( ) . pack ( ) ) ;
System. out. println ( ", Price : " + item. price ( ) ) ;
}
}
}
public class MealBuilder {
public Meal prepareVegMeal ( ) {
Meal meal = new Meal ( ) ;
meal. addItem ( new VegBurger ( ) ) ;
meal. addItem ( new Coke ( ) ) ;
return meal;
}
public Meal prepareNonVegMeal ( ) {
Meal meal = new Meal ( ) ;
meal. addItem ( new ChickenBurger ( ) ) ;
meal. addItem ( new Pepsi ( ) ) ;
return meal;
}
}
public class BuilderPatternDemo {
public static void main ( String[ ] args) {
MealBuilder mealBuilder = new MealBuilder ( ) ;
Meal vegMeal = mealBuilder. prepareVegMeal ( ) ;
System. out. println ( "Veg Meal" ) ;
vegMeal. showItems ( ) ;
System. out. println ( "Total Cost: " + vegMeal. getCost ( ) ) ;
Meal nonVegMeal = mealBuilder. prepareNonVegMeal ( ) ;
System. out. println ( "\n\nNon-Veg Meal" ) ;
nonVegMeal. showItems ( ) ;
System. out. println ( "Total Cost: " + nonVegMeal. getCost ( ) ) ;
}
}
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
单例
public class SingleObject {
private static SingleObject instance = new SingleObject ( ) ;
private SingleObject ( ) {
}
public static SingleObject getInstance ( ) {
return instance;
}
public void showMessage ( ) {
System. out. println ( "Hello World!" ) ;
}
public static void main ( String[ ] args) {
SingleObject object = SingleObject. getInstance ( ) ;
object. showMessage ( ) ;
}
}
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
public class Singleton1 {
private static Singleton1 instance;
private Singleton1 ( ) { }
public static Singleton1 getInstance ( ) {
if ( instance == null) {
instance = new Singleton1 ( ) ;
}
return instance;
}
public void showMessage ( ) {
System. out. println ( "Hello World!" ) ;
}
public static void main ( String[ ] args) {
Singleton1. getInstance ( ) . showMessage ( ) ;
}
}
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
public class Singleton2 {
private static Singleton2 instance;
private Singleton2 ( ) { }
public static synchronized Singleton2 getInstance ( ) {
if ( instance == null) {
instance = new Singleton2 ( ) ;
}
return instance;
}
public void showMessage ( ) {
System. out. println ( "Hello World!" ) ;
}
public static void main ( String[ ] args) {
Singleton2. getInstance ( ) . showMessage ( ) ;
}
}
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
public class Singleton3 {
private static Singleton3 instance = new Singleton3 ( ) ;
private Singleton3 ( ) { }
public static Singleton3 getInstance ( ) {
return instance;
}
public void showMessage ( ) {
System. out. println ( "Hello World!" ) ;
}
public static void main ( String[ ] args) {
Singleton3. getInstance ( ) . showMessage ( ) ;
}
}
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
public class Singleton4 {
private volatile static Singleton4 Singleton4;
private Singleton4 ( ) { }
public static Singleton4 getSingleton4 ( ) {
if ( Singleton4 == null) {
synchronized ( Singleton4. class ) {
if ( Singleton4 == null) {
Singleton4 = new Singleton4 ( ) ;
}
}
}
return Singleton4;
}
public void showMessage ( ) {
System. out. println ( "Hello World!" ) ;
}
public static void main ( String[ ] args) {
Singleton4. getSingleton4 ( ) . showMessage ( ) ;
}
}
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
public class Singleton5 {
private static class SingletonHolder {
private static final Singleton5 INSTANCE = new Singleton5 ( ) ;
}
private Singleton5 ( ) {
}
public static final Singleton5 getInstance ( ) {
return SingletonHolder. INSTANCE;
}
public void showMessage ( ) {
System. out. println ( "Hello World!" ) ;
}
public static void main ( String[ ] args) {
Singleton5. getInstance ( ) . showMessage ( ) ;
}
}
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
public enum Singleton6 {
INSTANCE;
public void whateverMethod ( ) {
}
}
享元
public interface Shape {
void draw ( ) ;
}
public class Circle implements Shape {
private String color;
private int x;
private int y;
private int radius;
public Circle ( String color) {
this . color = color;
}
. . .
@Override
public void draw ( ) {
System. out. println ( "Circle: Draw() [Color : " + color + ", x : " + x + ", y :" + y + ", radius :" + radius) ;
}
}
public class ShapeFactory {
private static final HashMap< String, Shape> circleMap = new HashMap < > ( ) ;
public static Shape getCircle ( String color) {
Circle circle = ( Circle) circleMap. get ( color) ;
if ( circle == null) {
circle = new Circle ( color) ;
circleMap. put ( color, circle) ;
System. out. println ( "Creating circle of color : " + color) ;
}
return circle;
}
}
public class FlyweightPatternDemo {
private static final String colors[ ] = { "Red" , "Green" , "Blue" , "White" , "Black" } ;
public static void main ( String[ ] args) {
for ( int i = 0 ; i < 20 ; ++ i) {
Circle circle = ( Circle) ShapeFactory. getCircle ( getRandomColor ( ) ) ;
circle. setX ( getRandomX ( ) ) ;
circle. setY ( getRandomY ( ) ) ;
circle. setRadius ( 100 ) ;
circle. draw ( ) ;
}
}
private static String getRandomColor ( ) {
return colors[ ( int ) ( Math. random ( ) * colors. length) ] ;
}
private static int getRandomX ( ) {
return ( int ) ( Math. random ( ) * 100 ) ;
}
private static int getRandomY ( ) {
return ( int ) ( Math. random ( ) * 100 ) ;
}
}
-- -- -- -- -- -- -- -- -- -- -- -- -
单纯享元模式 所有的享元对象都是可以共享的。
public interface Flyweight {
public void operation ( String state) ;
}
public class ConcreteFlyweight implements Flyweight {
private Character intrinsicState = null;
public ConcreteFlyweight ( Character state) {
this . intrinsicState = state;
}
@Override
public void operation ( String state) {
System. out. println ( "Intrinsic State = " + this . intrinsicState) ;
System. out. println ( "Extrinsic State = " + state) ;
}
}
public class FlyweightFactory {
private Map< Character, Flyweight> files = new HashMap < Character, Flyweight> ( ) ;
public Flyweight factory ( Character state) {
Flyweight fly = files. get ( state) ;
if ( fly == null) {
fly = new ConcreteFlyweight ( state) ;
files. put ( state, fly) ;
}
return fly;
}
}
复合享元模式
public interface Flyweight {
public void operation ( String state) ;
}
public class ConcreteFlyweight implements Flyweight {
private Character intrinsicState = null;
public ConcreteFlyweight ( Character state) {
this . intrinsicState = state;
}
@Override
public void operation ( String state) {
System. out. println ( "Intrinsic State = " + this . intrinsicState) ;
System. out. println ( "Extrinsic State = " + state) ;
}
}
public class ConcreteCompositeFlyweight implements Flyweight {
private Map< Character, Flyweight> files = new HashMap < Character, Flyweight> ( ) ;
public void add ( Character key , Flyweight fly) {
files. put ( key, fly) ;
}
@Override
public void operation ( String state) {
Flyweight fly = null;
for ( Object o : files. keySet ( ) ) {
fly = files. get ( o) ;
fly. operation ( state) ;
}
}
}
public class FlyweightFactory {
private Map< Character, Flyweight> files = new HashMap < Character, Flyweight> ( ) ;
public Flyweight factory ( List< Character> compositeState) {
ConcreteCompositeFlyweight compositeFly = new ConcreteCompositeFlyweight ( ) ;
for ( Character state : compositeState) {
compositeFly. add ( state, this . factory ( state) ) ;
}
return compositeFly;
}
public Flyweight factory ( Character state) {
Flyweight fly = files. get ( state) ;
if ( fly == null) {
fly = new ConcreteFlyweight ( state) ;
files. put ( state, fly) ;
}
return fly;
}
}
桥接
public interface DrawAPI {
public void drawCircle ( int radius, int x, int y) ;
}
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -
public class GreenCircle implements DrawAPI {
@Override
public void drawCircle ( int radius, int x, int y) {
System. out. println ( "Drawing Circle[ color: green, radius: "
+ radius + ", x: " + x+ ", " + y + "]" ) ;
}
}
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -
public class RedCircle implements DrawAPI {
@Override
public void drawCircle ( int radius, int x, int y) {
System. out. println ( "Drawing Circle[ color: red, radius: "
+ radius + ", x: " + x+ ", " + y + "]" ) ;
}
}
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -
public abstract class Shape {
protected DrawAPI drawAPI;
protected Shape ( DrawAPI drawAPI) {
this . drawAPI = drawAPI;
}
public abstract void draw ( ) ;
}
public class Circle extends Shape {
private int x;
private int y;
private int radius;
public Circle ( int x, int y, int radius, DrawAPI drawAPI) {
super ( drawAPI) ;
this . x = x;
this . y = y;
this . radius = radius;
}
public void draw ( ) {
drawAPI. drawCircle ( radius, x, y) ;
}
}
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -
public class BridgePatternDemo {
public static void main ( String[ ] args) {
Shape redCircle = new Circle ( 100 , 100 , 10 , new RedCircle ( ) ) ;
Shape greenCircle = new Circle ( 100 , 100 , 10 , new GreenCircle ( ) ) ;
redCircle. draw ( ) ;
greenCircle. draw ( ) ;
}
}
组合
public class Employee {
private String name;
private String dept;
private int salary;
private List< Employee> subordinates;
public Employee ( String name, String dept, int sal) {
this . name = name;
this . dept = dept;
this . salary = sal;
subordinates = new ArrayList < Employee> ( ) ;
}
public void add ( Employee e) {
subordinates. add ( e) ;
}
public void remove ( Employee e) {
subordinates. remove ( e) ;
}
public List< Employee> getSubordinates ( ) {
return subordinates;
}
public String toString ( ) {
return ( "Employee :[ Name : " + name + ", dept : " + dept + ", salary :" + salary + " ]" ) ;
}
}
public class CompositePatternDemo {
public static void main ( String[ ] args) {
Employee CEO = new Employee ( "John" , "CEO" , 30000 ) ;
Employee headSales = new Employee ( "Robert" , "Head Sales" , 20000 ) ;
Employee headMarketing = new Employee ( "Michel" , "Head Marketing" , 20000 ) ;
Employee clerk1 = new Employee ( "Laura" , "Marketing" , 10000 ) ;
Employee clerk2 = new Employee ( "Bob" , "Marketing" , 10000 ) ;
Employee salesExecutive1 = new Employee ( "Richard" , "Sales" , 10000 ) ;
Employee salesExecutive2 = new Employee ( "Rob" , "Sales" , 10000 ) ;
CEO. add ( headSales) ;
CEO. add ( headMarketing) ;
headSales. add ( salesExecutive1) ;
headSales. add ( salesExecutive2) ;
headMarketing. add ( clerk1) ;
headMarketing. add ( clerk2) ;
System. out. println ( CEO) ;
for ( Employee headEmployee : CEO. getSubordinates ( ) ) {
System. out. println ( headEmployee) ;
for ( Employee employee : headEmployee. getSubordinates ( ) ) {
System. out. println ( employee) ;
for ( Employee employee2 : employee. getSubordinates ( ) ) {
System. out. println ( employee2) ;
}
}
}
}
}
装饰器
public interface Shape {
void draw ( ) ;
}
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -
public class Circle implements Shape {
@Override
public void draw ( ) {
System. out. println ( "Shape: Circle" ) ;
}
}
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -
public class Rectangle implements Shape {
@Override
public void draw ( ) {
System. out. println ( "Shape: Rectangle" ) ;
}
}
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -
public abstract class ShapeDecorator implements Shape {
protected Shape decoratedShape;
public ShapeDecorator ( Shape decoratedShape) {
this . decoratedShape = decoratedShape;
}
public void draw ( ) {
decoratedShape. draw ( ) ;
}
}
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -
public class RedShapeDecorator extends ShapeDecorator {
public RedShapeDecorator ( Shape decoratedShape) {
super ( decoratedShape) ;
}
@Override
public void draw ( ) {
decoratedShape. draw ( ) ;
setRedBorder ( decoratedShape) ;
}
private void setRedBorder ( Shape decoratedShape) {
System. out. println ( "Border Color: Red" ) ;
}
}
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -
public class DecoratorPatternDemo {
public static void main ( String[ ] args) {
Shape circle = new Circle ( ) ;
Shape redCircle = new RedShapeDecorator ( new Circle ( ) ) ;
Shape redRectangle = new RedShapeDecorator ( new Rectangle ( ) ) ;
System. out. println ( "Circle with normal border" ) ;
circle. draw ( ) ;
System. out. println ( "\nCircle of red border" ) ;
redCircle. draw ( ) ;
System. out. println ( "\nRectangle of red border" ) ;
redRectangle. draw ( ) ;
}
}
适配器
public interface Target {
void method1 ( ) ;
void method2 ( ) ;
}
public class Adaptee {
public void method1 ( ) {
System. out. println ( "method 1" ) ;
}
}
类适配器
public class Adapter extends Adaptee implements Target {
@Override
public void method2 ( ) {
System. out. println ( "method 2" ) ;
}
}
class AdapterTest {
public static void main ( String[ ] args) {
Adapter adapter = new Adapter ( ) ;
adapter. method1 ( ) ;
adapter. method2 ( ) ;
}
}
对象适配器
public class Adapter implements Target {
private Adaptee adaptee;
public Adapter ( Adaptee adaptee) {
this . adaptee = adaptee;
}
@Override
public void method1 ( ) {
adaptee. method1 ( ) ;
}
@Override
public void method2 ( ) {
System. out. println ( "method 2" ) ;
}
}
接口适配器
interface 窗口{
public void 关闭( ) ;
public void 移动( ) ;
public ovid 最大化( ) ;
. . .
. . .
}
public abstract Frame implements 窗口{
public void 关闭( ) {
}
public void 移动( ) {
}
public ovid 最大化( ) {
}
. . .
}
public CloseFrame extends Frame {
public void 关闭( ) {
System. out. println ( "关闭窗口" ) ;
}
}
-- -- -- -- -- -- --
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -
public interface AdvancedMediaPlayer {
public void playVlc ( String fileName) ;
public void playMp4 ( String fileName) ;
}
public class Mp4Player implements AdvancedMediaPlayer {
@Override
public void playVlc ( String fileName) {
}
@Override
public void playMp4 ( String fileName) {
System. out. println ( "Playing Mp4 file. Name: " + fileName) ;
}
}
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -
public class VlcPlayer implements AdvancedMediaPlayer {
@Override
public void playVlc ( String fileName) {
System. out. println ( "Playing vlc file. Name: " + fileName) ;
}
@Override
public void playMp4 ( String fileName) {
}
}
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -
public interface MediaPlayer {
public void play ( String audioType, String fileName) ;
}
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -
public class AudioPlayer implements MediaPlayer {
MediaAdapter mediaAdapter;
@Override
public void play ( String audioType, String fileName) {
if ( audioType. equalsIgnoreCase ( "mp3" ) ) {
System. out. println ( "Playing mp3 file. Name: " + fileName) ;
}
else if ( audioType. equalsIgnoreCase ( "vlc" )
|| audioType. equalsIgnoreCase ( "mp4" ) ) {
mediaAdapter = new MediaAdapter ( audioType) ;
mediaAdapter. play ( audioType, fileName) ;
}
else {
System. out. println ( "Invalid media. " +
audioType + " format not supported" ) ;
}
}
}
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -
public class MediaAdapter implements MediaPlayer {
private AdvancedMediaPlayer advancedMusicPlayer;
public MediaAdapter ( String audioType) {
if ( audioType. equalsIgnoreCase ( "vlc" ) ) {
advancedMusicPlayer = new VlcPlayer ( ) ;
} else if ( audioType. equalsIgnoreCase ( "mp4" ) ) {
advancedMusicPlayer = new Mp4Player ( ) ;
}
}
@Override
public void play ( String audioType, String fileName) {
if ( audioType. equalsIgnoreCase ( "vlc" ) ) {
advancedMusicPlayer. playVlc ( fileName) ;
} else if ( audioType. equalsIgnoreCase ( "mp4" ) ) {
advancedMusicPlayer. playMp4 ( fileName) ;
}
}
}
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -
public class AdapterPatternDemo {
public static void main ( String[ ] args) {
AudioPlayer audioPlayer = new AudioPlayer ( ) ;
audioPlayer. play ( "mp3" , "beyond the horizon.mp3" ) ;
audioPlayer. play ( "mp4" , "alone.mp4" ) ;
audioPlayer. play ( "vlc" , "far far away.vlc" ) ;
audioPlayer. play ( "avi" , "mind me.avi" ) ;
}
}
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -
外观
public interface Shape {
void draw ( ) ;
}
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
public class Rectangle implements Shape {
@Override
public void draw ( ) {
System. out. println ( "Rectangle::draw()" ) ;
}
}
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
public class Circle implements Shape {
@Override
public void draw ( ) {
System. out. println ( "Circle::draw()" ) ;
}
}
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
public class Square implements Shape {
@Override
public void draw ( ) {
System. out. println ( "Square::draw()" ) ;
}
}
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
public class ShapeMaker {
private Shape circle;
private Shape rectangle;
private Shape square;
public ShapeMaker ( ) {
circle = new Circle ( ) ;
rectangle = new Rectangle ( ) ;
square = new Square ( ) ;
}
public void drawCircle ( ) {
circle. draw ( ) ;
}
public void drawRectangle ( ) {
rectangle. draw ( ) ;
}
public void drawSquare ( ) {
square. draw ( ) ;
}
}
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
public class FacadePatternDemo {
public static void main ( String[ ] args) {
ShapeMaker shapeMaker = new ShapeMaker ( ) ;
shapeMaker. drawCircle ( ) ;
shapeMaker. drawRectangle ( ) ;
shapeMaker. drawSquare ( ) ;
}
}
代理
public interface Image {
void display ( ) ;
}
public class RealImage implements Image {
private String fileName;
public RealImage ( String fileName) {
this . fileName = fileName;
loadFromDisk ( fileName) ;
}
public void display ( ) {
System. out. println ( "Displaying " + fileName) ;
}
private void loadFromDisk ( String fileName) {
System. out. println ( "Loading " + fileName) ;
}
}
public class ProxyImage implements Image {
private RealImage realImage;
private String fileName;
public ProxyImage ( String fileName) {
this . fileName = fileName;
}
@Override
public void display ( ) {
if ( realImage == null) {
realImage = new RealImage ( fileName) ;
}
realImage. display ( ) ;
}
}
public class ProxyPatternDemo {
public static void main ( String[ ] args) {
Image image = new ProxyImage ( "test_10mb.jpg" ) ;
image. display ( ) ;
System. out. println ( "" ) ;
image. display ( ) ;
}
}
过滤
public class Person implements Serializable {
private static final long serialVersionUID = 1 L;
private String name;
private String gender;
private String maritalStatus;
public Person ( String name, String gender, String maritalStatus) {
this . name = name;
this . gender = gender;
this . maritalStatus = maritalStatus;
}
. . .
}
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
public interface Criteria {
public List< Person> meetCriteria ( List< Person> persons) ;
}
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
public class CriteriaFemale implements Criteria {
@Override
public List< Person> meetCriteria ( List< Person> persons) {
List< Person> femalePersons = new ArrayList < Person> ( ) ;
for ( Person person : persons) {
if ( person. getGender ( ) . equalsIgnoreCase ( "FEMALE" ) ) {
femalePersons. add ( person) ;
}
}
return femalePersons;
}
}
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
public class CriteriaMale implements Criteria {
@Override
public List< Person> meetCriteria ( List< Person> persons) {
List< Person> malePersons = new ArrayList < Person> ( ) ;
for ( Person person : persons) {
if ( person. getGender ( ) . equalsIgnoreCase ( "MALE" ) ) {
malePersons. add ( person) ;
}
}
return malePersons;
}
}
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
public class CriteriaSingle implements Criteria {
@Override
public List< Person> meetCriteria ( List< Person> persons) {
List< Person> singlePersons = new ArrayList < Person> ( ) ;
for ( Person person : persons) {
if ( person. getMaritalStatus ( ) . equalsIgnoreCase ( "SINGLE" ) ) {
singlePersons. add ( person) ;
}
}
return singlePersons;
}
}
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
public class AndCriteria implements Criteria {
private Criteria criteria;
private Criteria otherCriteria;
public AndCriteria ( Criteria criteria, Criteria otherCriteria) {
this . criteria = criteria;
this . otherCriteria = otherCriteria;
}
@Override
public List< Person> meetCriteria ( List< Person> persons) {
List< Person> firstCriteriaPersons = criteria. meetCriteria ( persons) ;
return otherCriteria. meetCriteria ( firstCriteriaPersons) ;
}
}
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
public class OrCriteria implements Criteria {
private Criteria criteria;
private Criteria otherCriteria;
public OrCriteria ( Criteria criteria, Criteria otherCriteria) {
this . criteria = criteria;
this . otherCriteria = otherCriteria;
}
@Override
public List< Person> meetCriteria ( List< Person> persons) {
List< Person> firstCriteriaItems = criteria. meetCriteria ( persons) ;
List< Person> otherCriteriaItems = otherCriteria. meetCriteria ( persons) ;
for ( Person person : otherCriteriaItems) {
if ( ! firstCriteriaItems. contains ( person) ) {
firstCriteriaItems. add ( person) ;
}
}
return firstCriteriaItems;
}
}
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
public class CriteriaPatternDemo {
public static void main ( String[ ] args) {
List< Person> persons = new ArrayList < Person> ( ) ;
persons. add ( new Person ( "Robert" , "Male" , "Single" ) ) ;
persons. add ( new Person ( "John" , "Male" , "Married" ) ) ;
persons. add ( new Person ( "Laura" , "Female" , "Married" ) ) ;
persons. add ( new Person ( "Diana" , "Female" , "Single" ) ) ;
persons. add ( new Person ( "Mike" , "Male" , "Single" ) ) ;
persons. add ( new Person ( "Bobby" , "Male" , "Single" ) ) ;
Criteria male = new CriteriaMale ( ) ;
Criteria female = new CriteriaFemale ( ) ;
Criteria single = new CriteriaSingle ( ) ;
Criteria singleMale = new AndCriteria ( single, male) ;
Criteria singleOrFemale = new OrCriteria ( single, female) ;
System. out. println ( "Males: " ) ;
printPersons ( male. meetCriteria ( persons) ) ;
System. out. println ( "\nFemales: " ) ;
printPersons ( female. meetCriteria ( persons) ) ;
System. out. println ( "\nSingle Males: " ) ;
printPersons ( singleMale. meetCriteria ( persons) ) ;
System. out. println ( "\nSingle Or Females: " ) ;
printPersons ( singleOrFemale. meetCriteria ( persons) ) ;
}
public static void printPersons ( List< Person> persons) {
for ( Person person : persons) {
System. out. println ( "Person : [ Name : " + person. getName ( )
+ ", Gender : " + person. getGender ( )
+ ", Marital Status : " + person. getMaritalStatus ( )
+ " ]" ) ;
}
}
}
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
命令command
public class Stock {
private String name = "ABC" ;
private int quantity = 10 ;
public void buy ( ) {
System. out. println ( "Stock [ Name: " + name + ", Quantity: " + quantity + " ] bought" ) ;
}
public void sell ( ) {
System. out. println ( "Stock [ Name: " + name + ", Quantity: " + quantity + " ] sold" ) ;
}
}
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
public interface Order {
void execute ( ) ;
}
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
public class BuyStock implements Order {
private Stock abcStock;
public BuyStock ( Stock abcStock) {
this . abcStock = abcStock;
}
public void execute ( ) {
abcStock. buy ( ) ;
}
}
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
public class SellStock implements Order {
private Stock abcStock;
public SellStock ( Stock abcStock) {
this . abcStock = abcStock;
}
public void execute ( ) {
abcStock. sell ( ) ;
}
}
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
public class Broker {
private List< Order> orderList = new ArrayList < Order> ( ) ;
public void takeOrder ( Order order) {
orderList. add ( order) ;
}
public void placeOrders ( ) {
for ( Order order : orderList) {
order. execute ( ) ;
}
orderList. clear ( ) ;
}
}
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
public class CommandPatternDemo {
public static void main ( String[ ] args) {
Stock abcStock = new Stock ( ) ;
BuyStock buyStockOrder = new BuyStock ( abcStock) ;
SellStock sellStockOrder = new SellStock ( abcStock) ;
Broker broker = new Broker ( ) ;
broker. takeOrder ( buyStockOrder) ;
broker. takeOrder ( sellStockOrder) ;
broker. placeOrders ( ) ;
}
}
责任链chain
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -
public abstract class AbstractLogger {
public static int INFO = 1 ;
public static int DEBUG = 2 ;
public static int ERROR = 3 ;
protected int level;
protected AbstractLogger nextLogger;
public void setNextLogger ( AbstractLogger nextLogger) {
this . nextLogger = nextLogger;
}
public void logMessage ( int level, String message) {
if ( this . level <= level) {
write ( message) ;
}
if ( nextLogger != null) {
nextLogger. logMessage ( level, message) ;
}
}
abstract protected void write ( String message) ;
}
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -
public class ConsoleLogger extends AbstractLogger {
public ConsoleLogger ( int level) {
this . level = level;
}
@Override
protected void write ( String message) {
System. out. println ( "Standard Console::Logger: " + message) ;
}
}
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -
public class ErrorLogger extends AbstractLogger {
public ErrorLogger ( int level) {
this . level = level;
}
@Override
protected void write ( String message) {
System. out. println ( "Error Console::Logger: " + message) ;
}
}
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -
public class FileLogger extends AbstractLogger {
public FileLogger ( int level) {
this . level = level;
}
@Override
protected void write ( String message) {
System. out. println ( "File::Logger: " + message) ;
}
}
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -
public class ChainPatternDemo {
private static AbstractLogger getChainOfLoggers ( ) {
AbstractLogger errorLogger = new ErrorLogger ( AbstractLogger. ERROR) ;
AbstractLogger fileLogger = new FileLogger ( AbstractLogger. DEBUG) ;
AbstractLogger consoleLogger = new ConsoleLogger ( AbstractLogger. INFO) ;
fileLogger. setNextLogger ( consoleLogger) ;
errorLogger. setNextLogger ( fileLogger) ;
return errorLogger;
}
public static void main ( String[ ] args) {
AbstractLogger loggerChain = getChainOfLoggers ( ) ;
loggerChain. logMessage ( AbstractLogger. INFO, "This is an information." ) ;
loggerChain. logMessage ( AbstractLogger. DEBUG, "This is an debug level information." ) ;
loggerChain. logMessage ( AbstractLogger. ERROR, "This is an error information." ) ;
}
}
解释器interpreter
public interface Expression {
public boolean interpret ( String context) ;
}
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -
public class AndExpression implements Expression {
private Expression expr1 = null;
private Expression expr2 = null;
public AndExpression ( Expression expr1, Expression expr2) {
this . expr1 = expr1;
this . expr2 = expr2;
}
@Override
public boolean interpret ( String context) {
return expr1. interpret ( context) && expr2. interpret ( context) ;
}
}
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -
public class OrExpression implements Expression {
private Expression expr1 = null;
private Expression expr2 = null;
public OrExpression ( Expression expr1, Expression expr2) {
this . expr1 = expr1;
this . expr2 = expr2;
}
@Override
public boolean interpret ( String context) {
return expr1. interpret ( context) || expr2. interpret ( context) ;
}
}
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -
public class TerminalExpression implements Expression {
private String data;
public TerminalExpression ( String data) {
this . data = data;
}
@Override
public boolean interpret ( String context) {
if ( context. contains ( data) ) {
return true ;
}
return false ;
}
}
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -
public class InterpreterPatternDemo {
public static Expression getMaleExpression ( ) {
Expression robert = new TerminalExpression ( "Robert" ) ;
Expression john = new TerminalExpression ( "John" ) ;
return new OrExpression ( robert, john) ;
}
public static Expression getMarriedWomanExpression ( ) {
Expression julie = new TerminalExpression ( "Julie" ) ;
Expression married = new TerminalExpression ( "Married" ) ;
return new AndExpression ( julie, married) ;
}
public static void main ( String[ ] args) {
Expression isMale = getMaleExpression ( ) ;
Expression isMarriedWoman = getMarriedWomanExpression ( ) ;
System. out. println ( "John is male? " + isMale. interpret ( "John" ) ) ;
System. out. println ( "Julie is a married women? " + isMarriedWoman. interpret ( "Married Julie" ) ) ;
}
}
迭代子iterator
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
public interface Iterator {
public boolean hasNext ( ) ;
public Object next ( ) ;
}
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
public interface Container {
public Iterator getIterator ( ) ;
}
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
public class NameRepository implements Container {
public String names[ ] = { "Robert" , "John" , "Julie" , "Lora" } ;
@Override
public Iterator getIterator ( ) {
return new NameIterator ( ) ;
}
private class NameIterator implements Iterator {
int index;
@Override
public boolean hasNext ( ) {
if ( index < names. length) {
return true ;
}
return false ;
}
@Override
public Object next ( ) {
if ( this . hasNext ( ) ) {
return names[ index++ ] ;
}
return null;
}
}
}
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
public class IteratorPatternDemo {
public static void main ( String[ ] args) {
NameRepository namesRepository = new NameRepository ( ) ;
for ( Iterator iter = namesRepository. getIterator ( ) ; iter. hasNext ( ) ; ) {
String name = ( String) iter. next ( ) ;
System. out. println ( "Name : " + name) ;
}
}
}
中介者mediator
public class ChatRoom {
public static void showMessage ( User user, String message) {
System. out. println ( new Date ( ) . toString ( )
+ " [" + user. getName ( ) + "] : " + message) ;
}
}
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
public class User {
private String name;
public String getName ( ) {
return name;
}
public void setName ( String name) {
this . name = name;
}
public User ( String name) {
this . name = name;
}
public void sendMessage ( String message) {
ChatRoom. showMessage ( this , message) ;
}
}
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
public class MediatorPatternDemo {
public static void main ( String[ ] args) {
User robert = new User ( "Robert" ) ;
User john = new User ( "John" ) ;
robert. sendMessage ( "Hi! John!" ) ;
john. sendMessage ( "Hello! Robert!" ) ;
}
}
观察者observer
public class Subject {
private List< Observer> observers = new ArrayList < Observer> ( ) ;
private int state;
public int getState ( ) {
return state;
}
public void setState ( int state) {
this . state = state;
notifyAllObservers ( ) ;
}
public void attach ( Observer observer) {
observers. add ( observer) ;
}
public void notifyAllObservers ( ) {
for ( Observer observer : observers) {
observer. update ( ) ;
}
}
}
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -
public abstract class Observer {
protected Subject subject;
public abstract void update ( ) ;
}
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -
public class BinaryObserver extends Observer {
public BinaryObserver ( Subject subject) {
this . subject = subject;
this . subject. attach ( this ) ;
}
@Override
public void update ( ) {
System. out. println ( "Binary String: " + Integer. toBinaryString ( subject. getState ( ) ) ) ;
}
}
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -
public class HexaObserver extends Observer {
public HexaObserver ( Subject subject) {
this . subject = subject;
this . subject. attach ( this ) ;
}
@Override
public void update ( ) {
System. out. println ( "Hex String: " + Integer. toHexString ( subject. getState ( ) ) . toUpperCase ( ) ) ;
}
}
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -
public class OctalObserver extends Observer {
public OctalObserver ( Subject subject) {
this . subject = subject;
this . subject. attach ( this ) ;
}
@Override
public void update ( ) {
System. out. println ( "Octal String: " + Integer. toOctalString ( subject. getState ( ) ) ) ;
}
}
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -
public class ObserverPatternDemo {
public static void main ( String[ ] args) {
Subject subject = new Subject ( ) ;
new HexaObserver ( subject) ;
new OctalObserver ( subject) ;
new BinaryObserver ( subject) ;
System. out. println ( "First state change: 15" ) ;
subject. setState ( 15 ) ;
System. out. println ( "Second state change: 10" ) ;
subject. setState ( 10 ) ;
}
}
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -
备忘录memento
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
public class Memento {
private String state;
public Memento ( String state) {
this . state = state;
}
public String getState ( ) {
return state;
}
}
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
public class Originator {
private String state;
public void setState ( String state) {
this . state = state;
}
public String getState ( ) {
return state;
}
public Memento saveStateToMemento ( ) {
return new Memento ( state) ;
}
public void getStateFromMemento ( Memento Memento) {
state = Memento. getState ( ) ;
}
}
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
public class CareTaker {
private List< Memento> mementoList = new ArrayList < Memento> ( ) ;
public void add ( Memento state) {
mementoList. add ( state) ;
}
public Memento get ( int index) {
return mementoList. get ( index) ;
}
}
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
public class MementoPatternDemo {
public static void main ( String[ ] args) {
Originator originator = new Originator ( ) ;
CareTaker careTaker = new CareTaker ( ) ;
originator. setState ( "State #1" ) ;
originator. setState ( "State #2" ) ;
careTaker. add ( originator. saveStateToMemento ( ) ) ;
originator. setState ( "State #3" ) ;
careTaker. add ( originator. saveStateToMemento ( ) ) ;
originator. setState ( "State #4" ) ;
System. out. println ( "Current State: " + originator. getState ( ) ) ;
originator. getStateFromMemento ( careTaker. get ( 0 ) ) ;
System. out. println ( "First saved State: " + originator. getState ( ) ) ;
originator. getStateFromMemento ( careTaker. get ( 1 ) ) ;
System. out. println ( "Second saved State: " + originator. getState ( ) ) ;
}
}
模板方法template
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
public abstract class Game {
protected abstract void initialize ( ) ;
protected abstract void startPlay ( ) ;
protected abstract void endPlay ( ) ;
public final void play ( ) {
initialize ( ) ;
startPlay ( ) ;
endPlay ( ) ;
}
}
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
public class Cricket extends Game {
@Override
protected void endPlay ( ) {
System. out. println ( "Cricket Game Finished!" ) ;
}
@Override
protected void initialize ( ) {
System. out. println ( "Cricket Game Initialized! Start playing." ) ;
}
@Override
protected void startPlay ( ) {
System. out. println ( "Cricket Game Started. Enjoy the game!" ) ;
}
}
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
public class Football extends Game {
@Override
protected void endPlay ( ) {
System. out. println ( "Football Game Finished!" ) ;
}
@Override
protected void initialize ( ) {
System. out. println ( "Football Game Initialized! Start playing." ) ;
}
@Override
protected void startPlay ( ) {
System. out. println ( "Football Game Started. Enjoy the game!" ) ;
}
}
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
public class TemplatePatternDemo {
public static void main ( String[ ] args) {
Game game = new Cricket ( ) ;
game. play ( ) ;
System. out. println ( ) ;
game = new Football ( ) ;
game. play ( ) ;
}
}
访问者visitor
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -
public interface ComputerPart {
public void accept ( ComputerPartVisitor computerPartVisitor) ;
}
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -
public class Computer implements ComputerPart {
ComputerPart[ ] parts;
public Computer ( ) {
parts = new ComputerPart [ ] { new Mouse ( ) , new Keyboard ( ) , new Monitor ( ) } ;
}
@Override
public void accept ( ComputerPartVisitor computerPartVisitor) {
for ( int i = 0 ; i < parts. length; i++ ) {
parts[ i] . accept ( computerPartVisitor) ;
}
computerPartVisitor. visit ( this ) ;
}
}
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -
public class Keyboard implements ComputerPart {
@Override
public void accept ( ComputerPartVisitor computerPartVisitor) {
computerPartVisitor. visit ( this ) ;
}
}
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -
public class Monitor implements ComputerPart {
@Override
public void accept ( ComputerPartVisitor computerPartVisitor) {
computerPartVisitor. visit ( this ) ;
}
}
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -
public class Mouse implements ComputerPart {
@Override
public void accept ( ComputerPartVisitor computerPartVisitor) {
computerPartVisitor. visit ( this ) ;
}
}
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -
public interface ComputerPartVisitor {
public void visit ( Computer computer) ;
public void visit ( Mouse mouse) ;
public void visit ( Keyboard keyboard) ;
public void visit ( Monitor monitor) ;
}
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -
public class ComputerPartDisplayVisitor implements ComputerPartVisitor {
@Override
public void visit ( Computer computer) {
System. out. println ( "Displaying Computer." ) ;
}
@Override
public void visit ( Mouse mouse) {
System. out. println ( "Displaying Mouse." ) ;
}
@Override
public void visit ( Keyboard keyboard) {
System. out. println ( "Displaying Keyboard." ) ;
}
@Override
public void visit ( Monitor monitor) {
System. out. println ( "Displaying Monitor." ) ;
}
}
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -
public class VisitorPatternDemo {
public static void main ( String[ ] args) {
ComputerPart computer = new Computer ( ) ;
computer. accept ( new ComputerPartDisplayVisitor ( ) ) ;
}
}
状态state
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -
public interface State {
public void doAction ( Context context) ;
}
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -
public class StartState implements State {
public void doAction ( Context context) {
System. out. println ( "Player is in start state" ) ;
context. setState ( this ) ;
}
public String toString ( ) {
return "Start State" ;
}
}
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -
public class StopState implements State {
public void doAction ( Context context) {
System. out. println ( "Player is in stop state" ) ;
context. setState ( this ) ;
}
public String toString ( ) {
return "Stop State" ;
}
}
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -
public class Context {
private State state;
public Context ( ) {
state = null;
}
public void setState ( State state) {
this . state = state;
}
public State getState ( ) {
return state;
}
}
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -
public class StatePatternDemo {
public static void main ( String[ ] args) {
Context context = new Context ( ) ;
StartState startState = new StartState ( ) ;
startState. doAction ( context) ;
System. out. println ( context. getState ( ) . toString ( ) ) ;
StopState stopState = new StopState ( ) ;
stopState. doAction ( context) ;
System. out. println ( context. getState ( ) . toString ( ) ) ;
}
}
策略strategy
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
public interface Strategy {
public int doOperation ( int num1, int num2) ;
}
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
public class OperationAdd implements Strategy {
@Override
public int doOperation ( int num1, int num2) {
return num1 + num2;
}
}
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
public class OperationMultiply implements Strategy {
@Override
public int doOperation ( int num1, int num2) {
return num1 * num2;
}
}
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
public class OperationSubstract implements Strategy {
@Override
public int doOperation ( int num1, int num2) {
return num1 - num2;
}
}
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
public class Context {
private Strategy strategy;
public Context ( Strategy strategy) {
this . strategy = strategy;
}
public int executeStrategy ( int num1, int num2) {
return strategy. doOperation ( num1, num2) ;
}
}
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
public class StrategyPatternDemo {
public static void main ( String[ ] args) {
Context context = new Context ( new OperationAdd ( ) ) ;
System. out. println ( "10 + 5 = " + context. executeStrategy ( 10 , 5 ) ) ;
context = new Context ( new OperationSubstract ( ) ) ;
System. out. println ( "10 - 5 = " + context. executeStrategy ( 10 , 5 ) ) ;
context = new Context ( new OperationMultiply ( ) ) ;
System. out. println ( "10 * 5 = " + context. executeStrategy ( 10 , 5 ) ) ;
}
}
数组前m拦业务空传
数据访问对象模式dataAccess
组合实体模式compositeentity
前端控制模式frontcontroller
MVC 模式
拦截过滤器模式interceptingFilte
业务代表模式businessDelegate
服务器定位模式servicelocator
空对象模式nullobject
传输对象模式transferObject
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
public class Student {
private String name;
private int rollNo;
Student ( String name, int rollNo) {
this . name = name;
this . rollNo = rollNo;
}
g/ s. . .
}
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
public interface StudentDao {
public List< Student> getAllStudents ( ) ;
public Student getStudent ( int rollNo) ;
public void updateStudent ( Student student) ;
public void deleteStudent ( Student student) ;
}
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
public class StudentDaoImpl implements StudentDao {
List< Student> students;
public StudentDaoImpl ( ) {
students = new ArrayList < Student> ( ) ;
Student student1 = new Student ( "Robert" , 0 ) ;
Student student2 = new Student ( "John" , 1 ) ;
students. add ( student1) ;
students. add ( student2) ;
}
public void deleteStudent ( Student student) {
students. remove ( student. getRollNo ( ) ) ;
System. out. println ( "Student: Roll No " + student. getRollNo ( ) + ", deleted from database" ) ;
}
public List< Student> getAllStudents ( ) {
return students;
}
@Override
public Student getStudent ( int rollNo) {
return students. get ( rollNo) ;
}
@Override
public void updateStudent ( Student student) {
students. get ( student. getRollNo ( ) ) . setName ( student. getName ( ) ) ;
System. out. println ( "Student: Roll No " + student. getRollNo ( ) + ", updated in the database" ) ;
}
}
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
public class DaoPatternDemo {
public static void main ( String[ ] args) {
StudentDao studentDao = new StudentDaoImpl ( ) ;
for ( Student student : studentDao. getAllStudents ( ) ) {
System. out. println ( "Student: [RollNo : " + student. getRollNo ( ) + ", Name : " + student. getName ( ) + " ]" ) ;
}
Student student = studentDao. getAllStudents ( ) . get ( 0 ) ;
student. setName ( "Michael" ) ;
studentDao. updateStudent ( student) ;
studentDao. getStudent ( 0 ) ;
System. out. println ( "Student: [RollNo : " + student. getRollNo ( ) + ", Name : " + student. getName ( ) + " ]" ) ;
}
}
public class DependentObject1 {
private String data;
public void setData ( String data) {
this . data = data;
}
public String getData ( ) {
return data;
}
}
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
public class DependentObject2 {
private String data;
public void setData ( String data) {
this . data = data;
}
public String getData ( ) {
return data;
}
}
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
public class CoarseGrainedObject {
DependentObject1 do1 = new DependentObject1 ( ) ;
DependentObject2 do2 = new DependentObject2 ( ) ;
public void setData ( String data1, String data2) {
do1. setData ( data1) ;
do2. setData ( data2) ;
}
public String[ ] getData ( ) {
return new String [ ] { do1. getData ( ) , do2. getData ( ) } ;
}
}
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
public class CompositeEntity {
private CoarseGrainedObject cgo = new CoarseGrainedObject ( ) ;
public void setData ( String data1, String data2) {
cgo. setData ( data1, data2) ;
}
public String[ ] getData ( ) {
return cgo. getData ( ) ;
}
}
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
public class Client {
private CompositeEntity compositeEntity = new CompositeEntity ( ) ;
public void printData ( ) {
for ( int i = 0 ; i < compositeEntity. getData ( ) . length; i++ ) {
System. out. println ( "Data: " + compositeEntity. getData ( ) [ i] ) ;
}
}
public void setData ( String data1, String data2) {
compositeEntity. setData ( data1, data2) ;
}
}
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
public class CompositeEntityPatternDemo {
public static void main ( String[ ] args) {
Client client = new Client ( ) ;
client. setData ( "Test" , "Data" ) ;
client. printData ( ) ;
client. setData ( "Second Test" , "Data1" ) ;
client. printData ( ) ;
}
}
public class HomeView {
public void show ( ) {
System. out. println ( "Displaying Home Page" ) ;
}
}
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
public class StudentView {
public void show ( ) {
System. out. println ( "Displaying Student Page" ) ;
}
}
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
public class Dispatcher {
private StudentView studentView;
private HomeView homeView;
public Dispatcher ( ) {
studentView = new StudentView ( ) ;
homeView = new HomeView ( ) ;
}
public void dispatch ( String request) {
if ( request. equalsIgnoreCase ( "STUDENT" ) ) {
studentView. show ( ) ;
} else {
homeView. show ( ) ;
}
}
}
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
public class FrontController {
private Dispatcher dispatcher;
public FrontController ( ) {
dispatcher = new Dispatcher ( ) ;
}
private boolean isAuthenticUser ( ) {
System. out. println ( "User is authenticated successfully." ) ;
return true ;
}
private void trackRequest ( String request) {
System. out. println ( "Page requested: " + request) ;
}
public void dispatchRequest ( String request) {
trackRequest ( request) ;
if ( isAuthenticUser ( ) ) {
dispatcher. dispatch ( request) ;
}
}
}
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
public class FrontControllerPatternDemo {
public static void main ( String[ ] args) {
FrontController frontController = new FrontController ( ) ;
frontController. dispatchRequest ( "HOME" ) ;
frontController. dispatchRequest ( "STUDENT" ) ;
}
}
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -
public class Student {
private String rollNo;
private String name;
g/ s. . .
}
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -
public class StudentController {
private Student model;
private StudentView view;
public StudentController ( Student model, StudentView view) {
this . model = model;
this . view = view;
}
g/ s. . .
public void updateView ( ) {
view. printStudentDetails ( model. getName ( ) , model. getRollNo ( ) ) ;
}
}
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -
public class StudentView {
public void printStudentDetails ( String studentName, String studentRollNo) {
System. out. println ( "Student: " ) ;
System. out. println ( "Name: " + studentName) ;
System. out. println ( "Roll No: " + studentRollNo) ;
}
}
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -
public class MVCPatternDemo {
public static void main ( String[ ] args) {
Student model = retriveStudentFromDatabase ( ) ;
StudentView view = new StudentView ( ) ;
StudentController controller = new StudentController ( model, view) ;
controller. updateView ( ) ;
controller. setStudentName ( "John" ) ;
controller. updateView ( ) ;
}
private static Student retriveStudentFromDatabase ( ) {
Student student = new Student ( ) ;
student. setName ( "Robert" ) ;
student. setRollNo ( "10" ) ;
return student;
}
}
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
public interface Filter {
public void execute ( String request) ;
}
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
public class AuthenticationFilter implements Filter {
@Override
public void execute ( String request) {
System. out. println ( "Authenticating request: " + request) ;
}
}
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
public class DebugFilter implements Filter {
@Override
public void execute ( String request) {
System. out. println ( "request log: " + request) ;
}
}
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
public class Target {
public void execute ( String request) {
System. out. println ( "Executing request: " + request) ;
}
}
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
public class FilterChain {
private List< Filter> filters = new ArrayList < Filter> ( ) ;
private Target target;
public void addFilter ( Filter filter) {
filters. add ( filter) ;
}
public void execute ( String request) {
for ( Filter filter : filters) {
filter. execute ( request) ;
}
target. execute ( request) ;
}
public void setTarget ( Target target) {
this . target = target;
}
}
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
public class FilterManager {
FilterChain filterChain;
public FilterManager ( Target target) {
filterChain = new FilterChain ( ) ;
filterChain. setTarget ( target) ;
}
public void setFilter ( Filter filter) {
filterChain. addFilter ( filter) ;
}
public void filterRequest ( String request) {
filterChain. execute ( request) ;
}
}
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
public class Client {
FilterManager filterManager;
public void setFilterManager ( FilterManager filterManager) {
this . filterManager = filterManager;
}
public void sendRequest ( String request) {
filterManager. filterRequest ( request) ;
}
}
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
public class InterceptingFilterDemo {
public static void main ( String[ ] args) {
FilterManager filterManager = new FilterManager ( new Target ( ) ) ;
filterManager. setFilter ( new AuthenticationFilter ( ) ) ;
filterManager. setFilter ( new DebugFilter ( ) ) ;
Client client = new Client ( ) ;
client. setFilterManager ( filterManager) ;
client. sendRequest ( "HOME" ) ;
}
}
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -
public interface BusinessService {
public void doProcessing ( ) ;
}
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -
public class EJBService implements BusinessService {
public void doProcessing ( ) {
System. out. println ( "Processing task by invoking EJB Service" ) ;
}
}
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -
public class JMSService implements BusinessService {
public void doProcessing ( ) {
System. out. println ( "Processing task by invoking JMS Service" ) ;
}
}
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -
public class BusinessLookUp {
public BusinessService getBusinessService ( String serviceType) {
if ( serviceType. equalsIgnoreCase ( "EJB" ) ) {
return new EJBService ( ) ;
} else {
return new JMSService ( ) ;
}
}
}
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -
public class BusinessDelegate {
private BusinessLookUp lookupService = new BusinessLookUp ( ) ;
private BusinessService businessService;
private String serviceType;
public void setServiceType ( String serviceType) {
this . serviceType = serviceType;
}
public void doTask ( ) {
businessService = lookupService. getBusinessService ( serviceType) ;
businessService. doProcessing ( ) ;
}
}
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -
public class Client {
BusinessDelegate businessService;
public Client ( BusinessDelegate businessService) {
this . businessService = businessService;
}
public void doTask ( ) {
businessService. doTask ( ) ;
}
}
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -
public class BusinessDelegatePatternDemo {
public static void main ( String[ ] args) {
BusinessDelegate businessDelegate = new BusinessDelegate ( ) ;
businessDelegate. setServiceType ( "EJB" ) ;
Client client = new Client ( businessDelegate) ;
client. doTask ( ) ;
businessDelegate. setServiceType ( "JMS" ) ;
client. doTask ( ) ;
}
}
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
public interface Service {
public String getName ( ) ;
public void execute ( ) ;
}
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
public class Service1 implements Service {
@Override
public void execute ( ) {
System. out. println ( "Executing Service1" ) ;
}
@Override
public String getName ( ) {
return "Service1" ;
}
}
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
public class Service2 implements Service {
@Override
public void execute ( ) {
System. out. println ( "Executing Service2" ) ;
}
@Override
public String getName ( ) {
return "Service2" ;
}
}
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
public class Cache {
private List< Service> services;
public Cache ( ) {
services = new ArrayList < Service> ( ) ;
}
public Service getService ( String serviceName) {
for ( Service service : services) {
if ( service. getName ( ) . equalsIgnoreCase ( serviceName) ) {
System. out. println ( "Returning cached " + serviceName + " object" ) ;
return service;
}
}
return null;
}
public void addService ( Service newService) {
boolean exists = false ;
for ( Service service : services) {
if ( service. getName ( ) . equalsIgnoreCase ( newService. getName ( ) ) ) {
exists = true ;
}
}
if ( ! exists) {
services. add ( newService) ;
}
}
}
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
public class InitialContext {
public Object lookup ( String jndiName) {
if ( jndiName. equalsIgnoreCase ( "SERVICE1" ) ) {
System. out. println ( "Looking up and creating a new Service1 object" ) ;
return new Service1 ( ) ;
} else if ( jndiName. equalsIgnoreCase ( "SERVICE2" ) ) {
System. out. println ( "Looking up and creating a new Service2 object" ) ;
return new Service2 ( ) ;
}
return null;
}
}
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
public class ServiceLocator {
private static Cache cache;
static {
cache = new Cache ( ) ;
}
public static Service getService ( String jndiName) {
Service service = cache. getService ( jndiName) ;
if ( service != null) {
return service;
}
InitialContext context = new InitialContext ( ) ;
Service service1 = ( Service) context. lookup ( jndiName) ;
cache. addService ( service1) ;
return service1;
}
}
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
public class ServiceLocatorPatternDemo {
public static void main ( String[ ] args) {
Service service = ServiceLocator. getService ( "Service1" ) ;
service. execute ( ) ;
service = ServiceLocator. getService ( "Service2" ) ;
service. execute ( ) ;
service = ServiceLocator. getService ( "Service1" ) ;
service. execute ( ) ;
service = ServiceLocator. getService ( "Service2" ) ;
service. execute ( ) ;
}
}
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
public abstract class AbstractCustomer {
protected String name;
public abstract boolean isNil ( ) ;
public abstract String getName ( ) ;
}
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
public class NullCustomer extends AbstractCustomer {
@Override
public String getName ( ) {
return "Not Available in Customer Database" ;
}
@Override
public boolean isNil ( ) {
return true ;
}
}
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
public class RealCustomer extends AbstractCustomer {
public RealCustomer ( String name) {
this . name = name;
}
@Override
public String getName ( ) {
return name;
}
@Override
public boolean isNil ( ) {
return false ;
}
}
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
public class CustomerFactory {
public static final String[ ] names = { "Rob" , "Joe" , "Julie" } ;
public static AbstractCustomer getCustomer ( String name) {
for ( int i = 0 ; i < names. length; i++ ) {
if ( names[ i] . equalsIgnoreCase ( name) ) {
return new RealCustomer ( name) ;
}
}
return new NullCustomer ( ) ;
}
}
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
public class NullPatternDemo {
public static void main ( String[ ] args) {
AbstractCustomer customer1 = CustomerFactory. getCustomer ( "Rob" ) ;
AbstractCustomer customer2 = CustomerFactory. getCustomer ( "Bob" ) ;
AbstractCustomer customer3 = CustomerFactory. getCustomer ( "Julie" ) ;
AbstractCustomer customer4 = CustomerFactory. getCustomer ( "Laura" ) ;
System. out. println ( "Customers" ) ;
System. out. println ( customer1. getName ( ) ) ;
System. out. println ( customer2. getName ( ) ) ;
System. out. println ( customer3. getName ( ) ) ;
System. out. println ( customer4. getName ( ) ) ;
}
}
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -
public class StudentVO {
private String name;
private int rollNo;
StudentVO ( String name, int rollNo) {
this . name = name;
this . rollNo = rollNo;
}
g/ s. . .
}
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -
public class StudentBO {
List< StudentVO> students;
public StudentBO ( ) {
students = new ArrayList < StudentVO> ( ) ;
StudentVO student1 = new StudentVO ( "Robert" , 0 ) ;
StudentVO student2 = new StudentVO ( "John" , 1 ) ;
students. add ( student1) ;
students. add ( student2) ;
}
public void deleteStudent ( StudentVO student) {
students. remove ( student. getRollNo ( ) ) ;
System. out. println ( "Student: Roll No " + student. getRollNo ( ) + ", deleted from database" ) ;
}
public List< StudentVO> getAllStudents ( ) {
return students;
}
public StudentVO getStudent ( int rollNo) {
return students. get ( rollNo) ;
}
public void updateStudent ( StudentVO student) {
students. get ( student. getRollNo ( ) ) . setName ( student. getName ( ) ) ;
System. out. println ( "Student: Roll No " + student. getRollNo ( ) + ", updated in the database" ) ;
}
}
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -
public class TransferObjectPatternDemo {
public static void main ( String[ ] args) {
StudentBO studentBusinessObject = new StudentBO ( ) ;
for ( StudentVO student : studentBusinessObject. getAllStudents ( ) ) {
System. out. println ( "Student: [RollNo : " + student. getRollNo ( ) + ", Name : " + student. getName ( ) + " ]" ) ;
}
StudentVO student = studentBusinessObject. getAllStudents ( ) . get ( 0 ) ;
student. setName ( "Michael" ) ;
studentBusinessObject. updateStudent ( student) ;
studentBusinessObject. getStudent ( 0 ) ;
System. out. println ( "Student: [RollNo : " + student. getRollNo ( ) + ", Name : " + student. getName ( ) + " ]" ) ;
}
}