设计模式 java

Posted rocky-fang

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了设计模式 java相关的知识,希望对你有一定的参考价值。

 

 

A: 创造性模式

1. 工厂方法模式(FactoryMethod)

1.1 类图

1.2 代码1

public interface Pet
{
    public String petSound();
}

public class Cat implements Pet {
    @Override
    public String petSound() {
        return "Meaw Meaw...";
    }
}

public class Dog implements Pet {
    @Override
    public String petSound() {
        return "Bow Bow...";
    }
}

public class PetFactory {
    public Pet getPet(String petType){
        Pet pet = null;
        if("Bow".equals(petType)){
            pet = new Dog();
        }else if("Meaw".equals(petType)){
            pet = new Cat();
        }
        return pet;
    }
}

public class SampleFactoryMethod {
    public static void main(String[] args){
        PetFactory factory = new PetFactory();
        Pet pet = factory.getPet("Bow");
        System.out.println(pet.petSound());
    }
}
View Code

 代码2 (泛型)

public abstract class Product {
    public void method1(){
        //
    };
    public abstract void method2();
}

public class ConcreateProduct1 extends Product {
    @Override
    public void method2() {

    }
}

public class ConcreateProduct2 extends Product {
    @Override
    public void method2() {

    }
}

public abstract class Creator {
    public abstract <T extends Product> T createProduct(Class<T> c);
}

public class ConcreateCreator extends Creator {
    @Override
    public <T extends Product> T createProduct(Class<T> c) {
        Product instance = null;
        try {
            instance = (Product) Class.forName(c.getName()).newInstance();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        return (T)instance;
    }
}

public class Client {
    public static void main(String[] args){
        Creator creator = new ConcreateCreator();
        ConcreateProduct1 product1 = creator.createProduct(ConcreateProduct1.class);
    }
}
View Code

 

2. 抽象工厂模式(AbstractFactory)

2.1 类图

2.2 代码

package org.rocky.learn.designPattern.AbstractFactory;

/**
 * Created by admin on 2018/3/20.
 */
public abstract class Car {
    public abstract Parts getWheels();
    public abstract Parts getMirrors();
    public abstract Parts getEngine();
    public abstract Parts getBody();
}

package org.rocky.learn.designPattern.AbstractFactory;

/**
 * Created by admin on 2018/3/20.
 */
public class Parts {
    private String specification;
    public Parts(String specification){
        this.specification = specification;
    }
    public String getSpecification(){
        return specification;
    }
}

package org.rocky.learn.designPattern.AbstractFactory;

/**
 * Created by admin on 2018/3/20.
 */
public class BenQ extends Car  {
    @Override
    public Parts getWheels() {
        return new Parts("BenQ Wheels");
    }

    @Override
    public Parts getMirrors() {
        return new Parts("BenQ Mirriors");
    }

    @Override
    public Parts getEngine() {
        return new Parts("BenQ Engine");
    }

    @Override
    public Parts getBody() {
        return new Parts("BenQ body");
    }
}

package org.rocky.learn.designPattern.AbstractFactory;

/**
 * Created by admin on 2018/3/20.
 */
public class BMW extends Car {
    @Override
    public Parts getWheels() {
        return new Parts("BMW Wheels");
    }

    @Override
    public Parts getMirrors() {
        return new Parts("BMW Mirrors");
    }

    @Override
    public Parts getEngine() {
        return new Parts("BMW Engine");
    }

    @Override
    public Parts getBody() {
        return new Parts("BMW Body");
    }
}

package org.rocky.learn.designPattern.AbstractFactory;

/**
 * Created by admin on 2018/3/20.
 */
public class CarType {
    private Car car;
    public Car getCar(String carType){
        if("BenQ".equals(carType)){
            car =  new BenQ();
        }else if("BMW".equals(carType)){
            car = new BMW();
        }
        return car;
    }
    public static void main(String[] args){
        CarType carType = new CarType();
        Car benQ = carType.getCar("BenQ");
        System.out.println(benQ.getWheels().getSpecification());
        System.out.println(benQ.getMirrors().getSpecification());
        System.out.println(benQ.getEngine().getSpecification());
        System.out.println(benQ.getBody().getSpecification());
    }
}
View Code

 

3. 建造者模式(Builder)

克隆对象分为浅层复制和深层复制

3.1 类图

3.2 代码1

public interface CarPlan {
    public void setBase(String basement);
    public void setWheels(String structure);
}

public class Car implements  CarPlan {
    private String base;
    private String wheels;
    @Override
    public void setBase(String basement) {
        this.base = basement;
    }

    @Override
    public void setWheels(String structure) {
        this.wheels = structure;
    }

    @Override
    public String toString() {
        return "Car{" +
                "base=\'" + base + \'\\\'\' +
                ", wheels=\'" + wheels + \'\\\'\' +
                \'}\';
    }
}

public interface CarBuilder {
    public void buildBase();
    public void buildWheels();
    public Car getCar();
}

public class LowPriceCarBuilder implements CarBuilder {
    private Car car;
    public LowPriceCarBuilder(){
        car = new Car();
    }
    @Override
    public void buildBase() {
        car.setBase("Low Price Car Base Build");
    }

    @Override
    public void buildWheels() {
        car.setWheels("Low Price Car Wheels build");
    }

    @Override
    public Car getCar() {
        return this.car;
    }
}

public class MechanicalEngineer {
    private CarBuilder carBuilder;
    public MechanicalEngineer(CarBuilder carBuilder){
        this.carBuilder = carBuilder;
    }
    public Car getCar(){
        return carBuilder.getCar();
    }
    public void buildCar(){
        carBuilder.buildBase();
        carBuilder.buildWheels();
    }

    public static void main(String[] args){
        CarBuilder lowPriceCarBuilder = new LowPriceCarBuilder();
        MechanicalEngineer mechanicalEngineer = new MechanicalEngineer(lowPriceCarBuilder);
        mechanicalEngineer.buildCar();
        Car car = mechanicalEngineer.getCar();
        System.out.print("Builder constructor car.."+car);
    }
}
View Code

 java的api中 StringBuilder 和 StringBuffer是使用的生成器模式实例

代码2

public abstract  class House {
    protected Floor floor;
    protected Walls walls;
    protected Roof roof;

    public Floor getFloor() {
        return floor;
    }

    public void setFloor(Floor floor) {
        this.floor = floor;
    }

    public Walls getWalls() {
        return walls;
    }

    public void setWalls(Walls walls) {
        this.walls = walls;
    }

    public Roof getRoof() {
        return roof;
    }

    public void setRoof(Roof roof) {
        this.roof = roof;
    }
    public abstract String getRepresentation();
}

public interface Floor {
    public String getRepresentation();
}

public interface Walls {
    public String getRepresentation();
}

public interface Roof {
    public String getRepresentation();
}

package org.rocky.learn.designPattern.BuilderPattern2;

/**
 * Created by admin on 2018/3/20.
 */
public class WoodHouse extends House {
    @Override
    public String getRepresentation() {
        return "Build Wood House";
    }
}

package org.rocky.learn.designPattern.BuilderPattern2;

/**
 * Created by admin on 2018/3/20.
 */
public class WoodFloor implements Floor {
    @Override
    public String getRepresentation() {
        return "Build Wood Floor..";
    }
}

public class WoodWalls implements Walls {
    @Override
    public String getRepresentation() {
        return "Build Wood Walls";
    }
}

public class WoodRoof implements Roof {
    @Override
    public String getRepresentation() {
        return "Build Wood Roof";
    }
}

public abstract class HouseBuilder {
    protected House house;
    protected Floor floor;
    protected Walls walls;
    protected Roof roof;
    public abstract House createHouse();
    public abstract Floor createFloor();
    public abstract Walls createWalls();
    public abstract Roof createRoof();
}

public class WoodBuilder extends HouseBuilder {
    @Override
    public House createHouse() {
        house = new WoodHouse();
        return house;
    }

    @Override
    public Floor createFloor() {
        floor = new WoodFloor();
        return floor;
    }

    @Override
    public Walls createWalls() {
        walls = new WoodWalls();
        return walls;
    }

    @Override
    public Roof createRoof() {
        roof = new WoodRoof();
        return roof;
    }
}

public class HouseDirector {
    public House constructHouse(HouseBuilder houseBuilder){
        House house = houseBuilder.createHouse();
        System.out.println(house.getRepresentation());
        house.setFloor(houseBuilder.createFloor());
        System.out.println(house.getFloor().getRepresentation());
        house.setWalls(houseBuilder.createWalls());
        System.out.println(house.getWalls().getRepresentation());
        house.setRoof(houseBuilder.createRoof());
        System.out.println(house.getRoof().getRepresentation());
        return house;
    }
}

public class HouseClient {
    public static void main(String[] args){
        HouseDirector director = new HouseDirector();
        HouseBuilder houseBuilder = new WoodBuilder();
        director.constructHouse(houseBuilder);

    }
}
View Code

 

4. 单例模式(Singleton)

4.1 UML类图

4.2 代码1 被动实例化

package org.rocky.learn.designPattern.Singleton;

/**
 * Created by admin on 2018/3/20.
 */
public class SingletonPassive {
    private static  SingletonPassive singleton;
    private SingletonPassive(){}
    public static SingletonPassive getSingleton(){
        if(singleton == null){
            synchronized (SingletonPassive.class){
                if(singleton == null){
                    singleton = new SingletonPassive();
                }
            }
        }
        return singleton;
    }
}
View Code

代码2 主动实例化

public class SingletonProactive {
    private static SingletonProactive singleton = new SingletonProactive();
    private SingletonProactive(){}
    public static SingletonProactive getSingleton(){
        return singleton;
    }
}
View Code

 

5. 原型模式(prototype)

5.1 UML类图

5.2 代码

 

//浅拷贝
package org.rocky.learn.designPattern.PrototypePattern;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by admin on 2018/3/21.
 */
public class Plan implements Cloneable {
    //计划名称
    private String name;
    //任务级别
    private int level;
    //开始时间
    private Date startdate;
    //截止时间
    private Date enddate;
    //执行人员
    private List<String> executors = new ArrayList<String>();

    @Override
    public Plan clone(){
        try {
            return (Plan) super.clone();
        } catch (CloneNotSupportedException e) {
            e.printStackTrace();
        }
        return null;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Date getStartdate() {
        return startdate;
    }

    public void setStartdate(Date startdate) {
        this.startdate = startdate;
    }

    public Date getEnddate() {
        return enddate;
    }

    public void setEnddate(Date enddate) {
        this.enddate = enddate;
    }

    public List<String> getExecutors() {
        return executors;
    }

    public void setExecutors(List<String> executors) {
        this.executors = executors;
    }

    public int getLevel() {
        return level;
    }

    public void setLevel(int level) {
        this.level = level;
    }

    @Override
    public String toString() {
        return "[name=" + name + ", level=" + level + ", startdate=" + startdate + ", enddate=" + enddate
                + ", executors=" + executors + "]";
    }
}


//client
package org.rocky.learn.designPattern.PrototypePattern;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by admin on 2018/3/21.
 */
public class Client {
    private static final String format = "YYYY-mm-dd";
    public static void main(String[] args) throws ParseException {
        List<String> executors = new ArrayList<String>();
        executors.add("张三");
        executors.add("李四");

        Plan plan = new Plan();
        plan.setName("重构前端登录界面");
        plan.setLevel(1);
        plan.setStartdate(new SimpleDateFormat(format).parse("2017-08-07"));
        plan.setEnddate(new SimpleDateFormat(format).parse("2017-08-07"));
        plan.setExecutors(executors);

        Plan plan2 = plan.clone();
        plan2.setName("后端接口改造");
        plan2.setLevel(2);
        plan2.setStartdate(new SimpleDateFormat(format).parse("2017-08-07"));
        plan2.setEnddate(new SimpleDateFormat(format).parse("2017-08-07"));

        System.out.println("地址是否一样?"+(plan == plan2));
        System.out.println("plan.getName() == plan2.getName() "+(plan.getName() == plan2.getName()));
        System.out.println("plan.getLevel() == plan2.getLevel() "+(plan.getLevel() == plan2.getLevel()));
        System.out.println("plan.getStartdate() == plan2.getStartdate() "+(plan.getStartdate() == plan2.getStartdate()));
        System.out.println("plan.getEnddate() == plan2.getEnddate() "+(plan.getEnddate() == plan2.getEnddate()));
        System.out.println("plan.getExecutors() == plan2.getExecutors() "+(plan.getExecutors() == plan2.getExecutors()));
        System.out.println("plan:"+plan.toString());
        System.out.println("plan2:"+plan2.toString());

        //plan任务比较重,在给plan添加一个人
        executors.add("王五");
        plan.setExecutors(executors);

        System.out.println();
        System.out.println("地址是否一样?"+(plan == plan2));
        System.out.println("plan.getName() == plan2.getName() "+(plan.getName() == plan2.getName()));
        System.out.println("plan.getLevel() == plan2.getLevel() "+(plan.getLevel() == plan2.getLevel()));
        System.out.println("plan.getStartdate() == plan2.getStartdate() "+(plan.getStartdate() == plan2.getStartdate()));
        System.out.println("plan.getEnddate() == plan2.getEnddate() "+(plan.getEnddate() == plan2.getEnddate()));
        System.out.println("plan.getExecutors() == plan2.getExecutors() "+(plan.getExecutors() == plan2.getExecutors()));
        System.out.println("plan:"+plan.toString());
        System.out.println("plan2:"+plan2.toString());
    }
}

//深拷贝 clone方法
package org.rocky.learn.designPattern.PrototypePattern;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by admin on 2018/3/21.
 */
public class PlanDeeper {
    //计划名称
    private String name;
    //任务级别
    private int level;
    //开始时间
    private Date startdate;
    //截止时间
    private Date enddate;
    //执行人员
    private List<String> executors = new ArrayList<String>();

    @Override
    public Plan clone(){
        try {
            Plan plan = (Plan) super.clone();
            //引用类型的属性,需要处理
            if(this.getExecutors() != null){
                List<String> _executors = new ArrayList<String>();
                for(String s : this.getExecutors()){
                    _executors.add(s);
                }
                plan.setExecutors(_executors);
            }

            return plan;
        } catch (CloneNotSupportedException e) {
            e.printStackTrace();
        }
        return null;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Date getStartdate() {
        return startdate;
    }

    public void setStartdate(Date startdate) {
        this.startdate = startdate;
    }

    public Date getEnddate() {
        return enddate;
    }

    public void setEnddate(Date enddate) {
        this.enddate = enddate;
    }

    public List<String> getExecutors() {
        return executors;
    }

    public void setExecutors(List<String> executors) {
        this.executors = executors;
    }

    public int getLevel() {
        return level;
    }

    public void setLevel(int level) {
        this.level = level;
    }

    @Override
    public String toString() {
        return "[name=" + name + ", level=" + level + ", startdate=" + startdate + ", enddate=" + enddate
                + ", executors=" + executors + "]";
    }
}
View Code

 说明 见 3-2

B: 结构型模式

6.适配器模式(Adaptor)

6.1 UML类图

有两种应用适配器模式的方法

使用继承【类适配器】

使用关联【对象适配器】

 

6.2 代码

 a: 使用继承【类适配器】

public class Plug {
    private String specification;

    protected String getInput(){
        return specification;
    }

    public Plug(){
        specification = "3-Pin";
    }
}

public interface Socket {
    public String getInput();
}

public class ExpansionAdaptor extends Plug implements Socket {
    @Override
    public String getInput() {
        String input = super.getInput();
        input += " converted to 2-Pin";
        return input;
    }
}

public class Client {
    public static void main(String[] args){
         Socket socket = new ExpansionAdaptor();
        String input = socket.getInput();
        System.out.print(input);

    }
}
View Code

 b: 使用关联【对象适配器】

public class ExpansionAdapter implements Socket
{
    private Plug plug;
    public ExpansionAdapter(Plug p){
        plug = p;
    }
    @Override
    public String getInput() {
        String input = plug.getInput();
        input += " power converted to 2-Pin";
        return input;
    }
}

public java 查看寻呼机设计模式与片段。

201621123062《java程序设计》第九周作业总结

java代码在片段活动中不起作用

java 代码片段【JAVA】

# Java 常用代码片段

# Java 常用代码片段