1)工厂模式:简单工厂、工厂方法、抽象工厂
实例不用构造函数实现,而是类内部方法创建,从而根据不同的条件可以创建不同的实例。
public abstract class Factory{
public abstract Sample creator();
public abstract Sample2 creator(String name);
}
public class SimpleFactory extends Factory{
public Sample creator(){
.........
return new SampleA
}
public Sample2 creator(String name){
.........
return new Sample2A
}
}
public class BombFactory extends Factory{
public Sample creator(){
......
return new SampleB
}
public Sample2 creator(String name){
......
return new Sample2B
}
}
2)单子模式(singleton)
一个类要求只产生一个对象
package singleton;
public class singleton {
private static int counter;
private static singleton instance=new singleton();//必须要有的
public static singleton getSingleton(){ ///该方法只有再装载类运行一次,以后不再运行
return instance;
}
singleton(){ counter++;} //此构造方法只运行了一次
public static int s(){return counter;};}
package singleton;
public class test {
public static void main(String args[]){
for(int i=0;i<9;i++){
singleton single1=singleton.getSingleton();
singleton single2=singleton.getSingleton();
System.out.print(single1.s());
System.out.print(single2.s());
System.out.println();
}}}
3)模块方法
父类将多个子类的共同算法抽象出来生成一种方法,而数据有子类提供。
package module;
public abstract class vehicle {
public double distance;
public double time;
public double velocity;
public double v(){return velocity=distance/time;};
}
package module;
public class train extends vehicle{
private final double distance=1800;
private final double time=80;
private static train instance=new train();
private static train getVhicle1(){
return instance;
}
train(){super.distance=this.distance;super.time=this.time;};
public static void main(String args[]){
train tra=train.getVhicle1();
System.out.println(tra.v());
}
}
package module;
public class car extends vehicle{
private final double distance=1800;
private final double time=100;
private static car instance=new car();
private static car getVhicle2(){
return instance;
}
car(){super.distance=this.distance;super.time=this.time;};
public static void main(String args[]){
car tra=car.getVhicle2();
System.out.println(tra.v());
}
}
4)Builder模式。
生产汽车包括部件和组装过程。builder就是为了将部件和组装过程分开,将复杂对象的创建与部件的创建分开;复杂度逐渐增加。
builder接口:
concreteBuiler类:
director类:
builder接口:
package test;
public interface builder {
String wheel();
String window();
String steering();
String getResult();
}
concreteBuilder类:
package test;
public class concreteBuilder implements builder {
private String wl,ww,sg;
part wheel,window,steering;
product pr;
public String wheel(){this.wl="wheel";return wl;};
public String window(){this.ww="window";return ww;};
public String steering(){this.sg="steering";return sg;};
public String getResult(){
return this.wheel()+this.window()+this.steering();
};
}
director类:
package test;
public class director {
private builder buil;
public director (builder buil){
this.buil=buil;
};
public void construct(){
buil.wheel();
buil.window();
buil.steering();
buil.getResult();
};
}
5)原型模式prototype:
利用clone产生对象,即利用已有实例来产生实例;
package test;
/***************************/
abstract class AbstractWheel implements Cloneable{
public Object clone() {
Object o=null;
try {
o=super.clone();//调用父类,即Object的clone()
}
catch(CloneNotSupportedException e) {
System.err.println("APrototypeRam is not cloneable!");
}
return o;
}
}
/*********************/
abstract class AbstractWindow implements Cloneable{
public Object clone() {
Object o=null;
try {
o=super.clone();//调用父类,即Object的clone()
}
catch(CloneNotSupportedException e) {
System.err.println("APrototypeRam is not cloneable!");
}
return o;
}
}
/******************************/
class Wheel extends AbstractWheel {
public String toString(){
return "wheel";
};
}
/***********************************/
class Window extends AbstractWindow {
public String toString(){
return "window";
};
}
测试:
package test;
class test{
public static void main(String args[]){
Wheel wheel=new Wheel();
Window window=new Window();
Wheel wheel_clone=(Wheel)wheel.clone();
Window window_clone=(Window)window.clone();
System.out.println(wheel+" "+wheel_clone);
System.out.println(window+" "+window.clone());
};
};
6)外观模式 (facade)
将全部过程用一个类实现。
客户和子系统的类进行直接的交互会导致客户端对象和子系统(Figure1)之间高度耦合。任何的类似于对子系统中类的接口的修改,会对依赖于它的所有的客户类造成影响。
外观是一个能为子系统和客户提供简单接口的类。当正确的应用外观,客户不再直接和子系统中的类交互,而是与外观交互。外观承担与子系统中类交互的责任。实际上,外观是子系统与客户的接口,这样外观模式降低了子系统和客户的耦合度(Figure2).
package test;
interface Me{public String getName();};
interface Dispose{public void dispose(Me me);};
class Work implements Dispose{
public void dispose(Me me){
System.out.println(me.getName()+" "+"work");};};
class Eat implements Dispose{
public void dispose(Me me){
System.out.println(me.getName()+" "+"eat");
};
};
class Sleep implements Dispose{
public void dispose(Me me){
System.out.println(me.getName()+" "+"sleep");
};
};
class ConcreteMe implements Me{
private String name="sunxf";
private static ConcreteMe cm=new ConcreteMe();
public static ConcreteMe getCm(){
return cm;
}
public String getName(){return name;};
};
class Facade { //接口起到综合作用
Work work=new Work();
Eat eat=new Eat();
Sleep sleep=new Sleep();
Me me=(new ConcreteMe()).getCm();
public void dispose(){
work.dispose(me);
eat.dispose(me);
sleep.dispose(me);}
}
public class FacadeOneDay{
public static void main(String args[]){
Facade f=new Facade();
f.dispose();
}; }
7)代理模式
package test;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
interface Resource {
public void operationA();
public void operationB();
}
class ConcreteResource implements Resource {
public void operationA() {
System.out.println("Operation A.");
}
public void operationB() {
System.out.println("Operation B.");
}
}
class DynamicProxy implements InvocationHandler {
private Resource resource;
public DynamicProxy() {
resource = new ConcreteResource();
}
public Resource create() {
Resource returnResource = null;
returnResource = (Resource) Proxy.newProxyInstance(Resource.class.getClassLoader(), new Class[]{ Resource.class }, this);
return returnResource;
}
public Object invoke(Object obj, Method method, Object[] args) {
Object o = null;
try {
if (method.getName().equals("operationA")) {
//System.out.println("OperationA in Proxy");
o = method.invoke(resource, args);
} else {
o = method.invoke(resource, args);
}
} catch (Exception e) {
e.printStackTrace();
}
return o;
}
}
public class Test {
public static void main(String[] args) {
DynamicProxy proxy = new DynamicProxy();
Resource resource = proxy.create();
resource.operationA();
}
}
package test;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
interface Students{public void study();}; //抽象
class Monitor implements Students{ //具体
Monitor(){};
public void study(){
System.out.println("all are studying");
};
};
class ProxyStudents implements InvocationHandler{//代理 其中涉及到的类,都用Students接口
private Students students;
public Students bind(Students students){ //绑定
this.students=students;
return(Students)Proxy.newProxyInstance(students.getClass().getClassLoader(),students.getClass().getInterfaces(),this);
};
public Object invoke(Object proxy,Method method,Object[] args)throws Throwable{//触发的方法
return method.invoke(this.students, args);
};
};
public class MyTest {
public static void main(String args[]){
ProxyStudents ps=new ProxyStudents(); //生成学生代理的对象。
Students students=ps.bind(new Monitor()); //绑定Monitor为学生代理
students.study(); //相当于monitor.study()
};
}
8)adapter模式
基于类的Adapter模式的一般结构如下:Adaptee类为Adapter的父类,Adaptee类为适配源,适配目标(接口)也是Adapter的父类;基于类的Adapter模式比较适合应用于Adapter想修改Adaptee的部分方法的情况。基于对象的Adapter模式的一般结构如下:
Adaptee类对象为Adapter所依赖,适配目标(接口)是Adapter的父类;基于对象的Adapter模式比较适合应用于Adapter想为Adaptee添加新的方法的情况。但在Adaptee类的方法与Adapter类的方法不同名而实现相同功能的情况下,我们一般也使用基于对象的Adapter模式,在J2SE事件处理中,我们就大量使用了基于对象的Adapter模式。
package test;
class clientAdapter{ //用户接口
public static void main(String args[]){
Target target=new Adapter(new Cpu());
System.out.println(target.sendGraphic());
};
};
class Adapter extends Target{ //适配器转换 将cpu产生的二进制 转换为图形信息
private Cpu cpu;
Adapter(Cpu cpu){
this.cpu=cpu;
};
public String sendGraphic(){return cpu.getData();};
};
class Target{ //用户需要的图形信息
public String sendGraphic(){
return "send graphic";
};
};
class Cpu{ //cpu产生的二进制信息
public String getData(){return "CPU data";};
};
11)组合模式 composite
package test;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
abstract class Equipment{ //composite的定义 组件定义
private String name;
public abstract double netPrice();
public abstract double discountPrice();
public boolean add(Equipment equipment){return false;};
public boolean remove(Equipment equipment){return false;};
public Iterator iter(){return null;};
public Equipment(final String name){this.name=name;};
};
abstract class CompositeEquipment extends Equipment{ //容器定义
private int i=0;
private List container=new ArrayList();
public CompositeEquipment(String name){super(name);};
public boolean add(Equipment equipment){ //向容器中添加组件或者容器
this.container.add(equipment);
return true;
};
public double netPrice(){ //获得容器中所有组件或容器的属性和;
double netPrice=0;
Iterator iter=container.iterator();
for(;iter.hasNext();i++){netPrice+=((Equipment)iter.next()).netPrice();}
return netPrice;
};
public double discountPrice(){
double discountPrice=0;
Iterator iter=container.iterator();
for(;iter.hasNext();i++){discountPrice+=((Equipment)iter.next()).discountPrice();}
return discountPrice;
};
public boolean hasNext(){return i<container.size();};//容器中是否还有子容器或子组件
public Object next(){ //返回
if(hasNext()){return container.get(i);}
else
{System.out.println("return null");
return null;}
};}
class Disk extends Equipment{
public Disk(String name){super(name);};
public double netPrice(){return 1.;};
public double discountPrice(){return .5;};
};
class Chassis extends CompositeEquipment{
public Chassis(String name){super(name);};
public double netPrice(){return 1.+super.netPrice();};
public double discountPrice(){return .5+super.discountPrice();};
};
class Cabinet extends CompositeEquipment{
public Cabinet(String name){super(name);};
public double netPrice(){return 1.+super.netPrice();};
public double discountPrice(){return .5+super.discountPrice();};
};
public class Composite {
public static void main(String args[]){
Cabinet cabinet=new Cabinet("tower");
Chassis chassis=new Chassis("PC Chassis");
Chassis chassis2=new Chassis("pc chassis2");
cabinet.add(chassis);
chassis.add(new Disk("10 G"));
chassis.add(new Disk("20 G"));
chassis2.add(chassis);
cabinet.add(chassis2);
System.out.println("chassisnetPrice="+chassis.netPrice());
System.out.println("chassisdiscountPrice="+chassis.discountPrice());
System.out.println("chassis2netPrice="+chassis2.netPrice());
System.out.println("chassis2discountPrice="+chassis2.discountPrice());
System.out.println("netPrice="+cabinet.netPrice());
System.out.println("discountPrice="+cabinet.discountPrice());
};
}
12)装饰模式(Deractor)
package test;
import java.util.ArrayList;
import java.util.Iterator;
interface Job{public void doJob();};//抽象接口
class PlantTree implements Job{ //具体实现PlantTree
public void doJob(){
System.out.println("plant tree");
};
};
class Decorator implements Job{ //装饰可向PlantTree中添加更多的方法和功能;
private Job job;
private ArrayList others=new ArrayList();//其他功能打包
public Decorator(Job job){
this.job=job;
others.add("dig hole");
others.add("find tree");
};
public void doJob(){
newMethod();
};
public void newMethod(){
otherMethod();
job.doJob();
};
public void otherMethod(){ //定义其他功能;
Iterator iterator=others.iterator();
while(iterator.hasNext()){
System.out.println((String)iterator.next());
};
};
};
public class testDecorator {
public static void main(String args[]){
Job planttree=new PlantTree();
Job decorator=new Decorator(planttree);
decorator.doJob(); };
}
13)chain of Responsebility(责任链)
package test;
interface Procedure {
public abstract void nextProcedure(Procedure procedure); //下一工序
public abstract void executeProcedure(String aim); //执行工序
}
class ConcreteProcedure implements Procedure{
private Procedure nextProcedure = null;
String[] procedureName ={"Design","Code","Test"};
public void nextProcedure(Procedure procedure) { //下一工序
nextProcedure = procedure;
}
public void executeProcedure(String currentProcedure) { //执行工序
for(int i=0;i<procedureName.length;i++){
if(currentProcedure.equals(procedureName[i])) {//如果当前工序和该工序相符
System.out.println("第"+(i+1)+"道工序: "+procedureName[i]);
} else {
if(nextProcedure != null) { //如果当前工序和该工序不相符则转入下一工序
nextProcedure.executeProcedure(currentProcedure);
}
}
}
}
};
public class Chain {
public static void main(String[] args) {
ConcreteProcedure cp=new ConcreteProcedure();
cp.executeProcedure("Code");
cp.executeProcedure("Test");
cp.executeProcedure("Design");
}}
15)Command模式
将这些命令封装成在一个类中,然后用户(调用者)再对这个类进行操作,这就是Command模式
package test;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
interface Command{ //抽象命令
public abstract String execute();
};
class Engineer implements Command{ //具体命令
public String execute(){
return "i am an engineer";
};
};
class Programmer implements Command{ //具体命令
public String execute(){
return "i am a programmer";
};
};
class Politician implements Command{ //具体命令
public String execute(){
return "i am a politician";
};
};
class Encapsulation{ //将不同的具体命令封装在一个类中
public static List encapsulationCommand(){
List queue=new ArrayList();
queue.add(new Engineer());
queue.add(new Programmer());
queue.add(new Politician());
return queue;
};
};
public class testCommand {
public static void main(String args[]){ //通过显示全部命令验证Command模式
List queue=Encapsulation.encapsulationCommand();
for(Iterator it=queue.iterator();it.hasNext();){System.out.println(((Command)it.next()).execute());};
};
}
17)State状态
取代if else if 处理经常跳转,并多方向,还有跳转后处理大事件
package test;
/*Water三种状态Ice LiquidWater steam 三种状态的转换heat cold*/
interface Water {
public void handleHeat(Context_ c);
public void handleCold(Context_ c);
public void getUsage();
}
//冰状态
class Ice implements Water{
public void handleHeat(Context_ c) {
c.setWater(new LiquidWater());
}
public void handleCold(Context_ c) {
c.setWater(new Ice());
}
public void getUsage() {
System.out.println("We can skate now");
}
}
//水状态
class LiquidWater implements Water{
public void handleHeat(Context_ c) {
c.setWater(new Steam());
}
public void handleCold(Context_ c) {
c.setWater(new Ice());
}
public void getUsage() {
System.out.println("It can be drink");
}
}
//水蒸气状态
class Steam implements Water {
public void handleHeat(Context_ c) {
c.setWater(new Steam());
}
public void handleCold(Context_ c) {
c.setWater(new LiquidWater());
}
public void getUsage() {
System.out.println("It can warm bread now");
}
}
/*状态机起到设定初始条件,并触发状态转换*/
class Context_ {
private Water water = null;
public Water getWater() {
return water;
}
public void setWater(Water water) {
this.water = water;
}
public void HeatUp() {
water.handleHeat(this);
water.getUsage();
}
public void Cold() {
water.handleCold(this);
water.getUsage();
}
}
public class testState {
public static void main(String[] args) {
Water water=new Ice();
Context_ c=new Context_();
c.setWater(water);
c.HeatUp();
c.HeatUp();
c.Cold();
c.Cold();
c.HeatUp();
}
}
浙公网安备 33010602011771号