java 各种设计模式学习

来源:互联网 发布:中国gis软件 编辑:程序博客网 时间:2024/05/17 23:12
工厂模式

工厂模式主要是为创建对象提供过渡接口,以便将创建对象的具体过程屏蔽隔离起来,达到提高灵活性的目的。

//抽象产品角色public interface Moveable {    void run();}//具体产品角色public class Plane implements Moveable {    @Override    public void run() {        System.out.println("plane....");    }}public class Broom implements Moveable {    @Override    public void run() {        System.out.println("broom.....");    }}//抽象工厂public abstract class VehicleFactory {    abstract Moveable create();}//具体工厂public class PlaneFactory extends VehicleFactory{    public Moveable create() {        return new Plane();    }}public class BroomFactory extends VehicleFactory{    public Moveable create() {        return new Broom();    }}//测试类public class Test {    public static void main(String[] args) {        VehicleFactory factory = new BroomFactory();        Moveable m = factory.create();        m.run();    }}



1.命令模式

package com.controller;/** * @author: * @TODO:命令模式 */public class CommandTest {public static void main(String[] args) {Tv myTv = new Tv();CommandOn on = new CommandOn(myTv);CommandOff off = new CommandOff(myTv);CommandChange channel = new CommandChange(myTv, 2);Control control = new Control(on, off, channel);control.turnOn();control.changeChannel();control.turnOff();}}/** * @author: * @TODO:命令借口 */interface Command {void execute();}class Tv {public int currentChannel = 0;public void turnOn() {System.out.println("The televisino is on.");}public void turnOff() {System.out.println("The television is off.");}public void changeChannel(int channel) {this.currentChannel = channel;System.out.println("Now TV channel is " + channel);}}// 开机命令ConcreteCommandclass CommandOn implements Command {private Tv myTv;public CommandOn(Tv tv) {myTv = tv;}public void execute() {myTv.turnOn();}}// 关机命令ConcreteCommandclass CommandOff implements Command {private Tv myTv;public CommandOff(Tv tv) {myTv = tv;}public void execute() {myTv.turnOff();}}// 频道切换命令ConcreteCommandclass CommandChange implements Command {private Tv myTv;private int channel;public CommandChange(Tv tv, int channel) {myTv = tv;this.channel = channel;}public void execute() {myTv.changeChannel(channel);}}// 可以看作是遥控器Invokerclass Control {private Command onCommand, offCommand, changeChannel;public Control(Command on, Command off, Command channel) {onCommand = on;offCommand = off;changeChannel = channel;}public void turnOn() {onCommand.execute();}public void turnOff() {offCommand.execute();}public void changeChannel() {changeChannel.execute();}}


转自:http://blog.csdn.net/jason0539/article/details/45110355

2.组合模式

package com.controller;import java.util.ArrayList;import java.util.List;public class ComponentTest {public abstract class Component {String name;public abstract void add(Component c);public abstract void remove(Component c);public abstract void eachChild();}// 组合部件类public class Leaf extends Component {// 叶子节点不具备添加的能力,所以不实现@Overridepublic void add(Component c) {System.out.println("");}// 叶子节点不具备添加的能力必然也不能删除@Overridepublic void remove(Component c) {System.out.println("");}// 叶子节点没有子节点所以显示自己的执行结果@Overridepublic void eachChild() {System.out.println(name + "执行了");}}// 组合类public class Composite extends Component {// 用来保存节点的子节点List<Component> list = new ArrayList<Component>();// 添加节点 添加部件@Overridepublic void add(Component c) {list.add(c);}// 删除节点 删除部件@Overridepublic void remove(Component c) {list.remove(c);}// 遍历子节点@Overridepublic void eachChild() {System.out.println(name + "执行了");for (Component c : list) {c.eachChild();}}}public static void main(String[] args) {ComponentTest demo = new ComponentTest();// 构造根节点Composite rootComposite = demo.new Composite();rootComposite.name = "根节点";// 左节点Composite compositeLeft = demo.new Composite();compositeLeft.name = "左节点";// 构建右节点,添加两个叶子几点,也就是子部件Composite compositeRight = demo.new Composite();compositeRight.name = "右节点";Leaf leaf1 = demo.new Leaf();leaf1.name = "右-子节点1";Leaf leaf2 = demo.new Leaf();leaf2.name = "右-子节点2";compositeRight.add(leaf1);compositeRight.add(leaf2);// 左右节点加入 根节点rootComposite.add(compositeRight);rootComposite.add(compositeLeft);// 遍历组合部件rootComposite.eachChild();}}


转自:http://blog.csdn.net/jason0539/article/details/22642281

3.装饰模式

package com.controller;//定义公共接口interface Human {public void wearClothes();public void walkToWhere();}// 定义装饰者abstract class Decorator implements Human {private Human human;public Decorator(Human human) {this.human = human;}public void wearClothes() {human.wearClothes();}public void walkToWhere() {human.walkToWhere();}}// 下面定义三种装饰,这是第一个,第二个第三个功能依次细化,即装饰者的功能越来越多class Decorator_zero extends Decorator {public Decorator_zero(Human human) {super(human);}public void goHome() {System.out.println("进房子。。");}public void findMap() {System.out.println("书房找找Map。。");}@Overridepublic void wearClothes() {super.wearClothes();goHome();}@Overridepublic void walkToWhere() {super.walkToWhere();findMap();}}// 定义被装饰者,被装饰者初始状态有些自己的装饰class Person implements Human {@Overridepublic void wearClothes() {System.out.println("穿什么呢。。");}@Overridepublic void walkToWhere() {System.out.println("去哪里呢。。");}}// 测试类,看一下你就会发现,跟java的I/O操作有多么相似public class DecoratorTest {public static void main(String[] args) {Human person = new Person();Decorator decorator = new Decorator_zero(person);decorator.wearClothes();decorator.walkToWhere();}}


转自:http://blog.csdn.net/jason0539/article/details/22713711

4.原型模式

package com.controller;import net.sf.cglib.beans.BeanCopier;/** * @author: * @TODO:原型模式 */public class PrototypeTest extends Prototype{public static void main(String[] args)  {BO bo = new BO();bo.setAge(27);CloneClass cp = new CloneClass("lau",bo);CloneClass clonecp = null ;CloneClass beanCopy = new CloneClass() ;try {clonecp = (CloneClass)cp.clone();} catch (CloneNotSupportedException e) {e.printStackTrace();}        clonecp.doIt();        BeanCopier bc = BeanCopier.create(CloneClass.class, CloneClass.class, false);        bc.copy(cp, beanCopy, null);        beanCopy.doIt();}}/** * @author: * @TODO:克隆类   */class Prototype implements Cloneable{@Overridepublic Object clone() throws CloneNotSupportedException {Prototype prototype = null;            try{                prototype = (Prototype)super.clone();            }catch(CloneNotSupportedException e){                e.printStackTrace();        }        return prototype;}}class CloneClass extends Prototype {private String name ;private BO bo ;public CloneClass(){}public CloneClass(String name,BO bo){this.name = name ;this.bo = bo ;}public BO getBo() {return bo;}public void setBo(BO bo) {this.bo = bo;}public String getName() {return name;}public void setName(String name) {this.name = name;}public void doIt(){System.out.println(name+" I am "+bo.getAge());}}class BO{private int age ;public int getAge() {return age;}public void setAge(int age) {this.age = age;}}


转自:http://blog.csdn.net/jason0539/article/details/23158081

5.代理模式

package com.controller;/** * @author: * @TODO:代理模式 */public class ProxyTest {public static void main(String[] args) {People people_1 = new People();people_1.setCash(60000);people_1.setUsername("jeck");People people_2 = new People();people_2.setCash(40000);people_2.setUsername("rose");People people_3 = new People();people_3.setCash(0);people_3.setUsername("tom");people_3.setVip("vip");ProxyClass proxy_buy = new ProxyClass();proxy_buy.setPeople(people_1);proxy_buy.buy_mycar();proxy_buy.setPeople(people_2);proxy_buy.buy_mycar();proxy_buy.setPeople(people_3);proxy_buy.buy_mycar();}}interface CarShop {public void buy_mycar();}class People implements CarShop {private int cash;private String vip;private String username;@Overridepublic void buy_mycar() {System.out.print(username + "是vip 客户,可以直接购买新车!");}public int getCash() {return cash;}public void setCash(int cash) {this.cash = cash;}public String getUsername() {return username;}public void setUsername(String username) {this.username = username;}public String getVip() {return vip;}public void setVip(String vip) {this.vip = vip;}}class ProxyClass implements CarShop {private People people;public People getPeople() {return people;}public void setPeople(People people) {this.people = people;}@Overridepublic void buy_mycar() {if (people.getVip() == "vip") {people.buy_mycar();return;}if (people.getCash() >= 50000) {System.out.println(people.getUsername() + " 买了新车,交易结束!");} else {System.out.println(people.getUsername() + " 钱不够,不能买车,继续比赛!");}}}


转自:http://blog.csdn.net/jason0539/article/details/22974405

6.策略模式

package com.controller;/** * @author: * @TODO:策略模式 */public class StrategyTest {public static void main(String[] args) {Context context;System.out.println("----------刚到吴国使用第一个锦囊---------------");context = new Context(new BackDoor());context.operate();System.out.println("\n");System.out.println("----------刘备乐不思蜀使用第二个锦囊---------------");context.setStrategy(new GivenGreenLight());context.operate();System.out.println("\n");System.out.println("----------孙权的追兵来了,使用第三个锦囊---------------");context.setStrategy(new BlackEnemy());context.operate();System.out.println("\n");}}/** * @author: * @TODO:策略接口 */interface IStrategy {public void operate();}class BackDoor implements IStrategy {@Overridepublic void operate() {System.out.println("找乔国老帮忙,让吴国太给孙权施加压力,使孙权不能杀刘备");}}class GivenGreenLight implements IStrategy {@Overridepublic void operate() {System.out.println("求吴国太开个绿灯,放行");}}class BlackEnemy implements IStrategy {@Overridepublic void operate() {System.out.println("孙夫人断后,挡住追兵");}}class Context {private IStrategy strategy;// 构造函数,要你使用哪个妙计public Context(IStrategy strategy) {this.strategy = strategy;}public void setStrategy(IStrategy strategy) {this.strategy = strategy;}public void operate() {this.strategy.operate();}}


转自:http://blog.csdn.net/jason0539/article/details/45007553
0 0