工厂设计模式
interface Fruit{
void show();
}
class Apple implements Fruit{
@Override
public void show(){
System.out.println("apple");
}
}
class Banana implements Fruit{
@Override
public void show(){
System.out.println("banana");
}
}
public class FruitFactory{
private final Integer TYPE_APPLE = 1;
private final Integer TYPE_BANANA = 2;
public Fruit buy(Integer type){
switch (type) {
case 1: return new Apple();
case 2: return new Banana();
default:return null;
}
}
}
//测试:
public class Test {
public static void main(String[] args) {
new FruitFactory().buy(1).show();
new FruitFactory().buy(2).show();
}
}
//apple
//banana
单例设计模式
饿汉式
public class HungrySingle {
private static final HungrySingle hungry = new HungrySingle();
private HungrySingle(){
//构造方法
}
public static HungrySingle getHungry(){
return hungry;
}
}
public class Test {
public static void main(String[] args) {
System.out.println(HungrySingle.getHungry() == HungrySingle.getHungry());
}
}
//true
懒汉式
public class LazySingle {
//volatile 防重排
private static volatile LazySingle lazySingle;
private LazySingle(){
//构造方法
}
/*
//普通
public static LazySingle getLazySingle(){
if(lazySingle == null){
lazySingle = new LazySingle();
}
return lazySingle;
}
*/
/*
//加锁
public static synchronized LazySingle getLazySingle(){
if(lazySingle == null){
lazySingle = new LazySingle();
}
return lazySingle;
}*/
//双重加锁
public static LazySingle getLazySingle(){
if(lazySingle == null){
synchronized (LazySingle.class){
if(lazySingle == null){
lazySingle = new LazySingle();
}
}
}
return lazySingle;
}
}
public class Test {
public static void main(String[] args) {
System.out.println(LazySingle.getLazySingle() == LazySingle.getLazySingle());
}
}
//true
内部类方法:
public class LazySingleClass {
private LazySingleClass(){
//构造方法
}
private static class Inner{
private static LazySingleClass lazySingleClass = new LazySingleClass();
}
public static LazySingleClass getLazySingleClass(){
return Inner.lazySingleClass;
}
}
public class Test {
public static void main(String[] args) {
System.out.println(LazySingleClass.getLazySingleClass() == LazySingleClass.getLazySingleClass());
}
}
//true
枚举单例
public enum SingleEnum {
SINGLE_ENUM;
SingleEnum(){
//构造方法
}
}
public class Test {
public static void main(String[] args) {
System.out.println(SingleEnum.SINGLE_ENUM == SingleEnum.SINGLE_ENUM);
}
}
//true
建造者模式
public class Student {
public static class Builder{
private String name;
private Integer id;
private Character sex;
private Integer age;
private String school;
public Builder(String name, Integer id) {
this.name = name;
this.id = id;
}
public Builder setSex(Character sex) {
this.sex = sex;
return this;
}
public Builder setAge(Integer age) {
this.age = age;
return this;
}
public Builder setSchool(String school) {
this.school = school;
return this;
}
public Student build(){
return new Student(this);
}
}
private String name;
private Integer id;
private Character sex;
private Integer age;
private String school;
private Student(Builder builder) {
this.name = builder.name;
this.id = builder.id;
this.sex = builder.sex;
this.age = builder.age;
this.school = builder.school;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", id=" + id +
", sex=" + sex +
", age=" + age +
", school='" + school + '\'' +
'}';
}
}
public class Test {
public static void main(String[] args) {
Student student = new Student.Builder("emy",101055).setSex('男').build();
System.out.println(student.toString());
Student student1 = new Student.Builder("emy",101055).setSex('男').setSchool("Guess").build();
System.out.println(student1.toString());
}
}
//Student{name='emy', id=101055, sex=男, age=null, school='null'}
//Student{name='emy', id=101055, sex=男, age=null, school='Guess'}
原型模式
public class A extends ProtoType<A>{
private Integer id;
public A(Integer id) throws InterruptedException {
Thread.sleep(5000);
this.id = id;
}
@Override
public String toString() {
return "A{" +
"id=" + id +
'}';
}
}
public class ProtoType<T extends ProtoType> implements Cloneable{
public T copy() throws CloneNotSupportedException {
return (T)super.clone();
}
}
public class Test {
public static void main(String[] args) throws Exception{
A a = new A(999);
/*
//很慢
for(int i=0;i<10;i++){
A a1 = new A(999);
System.out.println(a1);
}
*/
for(int i=0;i<5;i++){
A a1 = a.copy();
System.out.println(a1);
}
}
}
//5s后第一个出来,后面的立刻出来
//A{id=999}
//A{id=999}
//A{id=999}
//A{id=999}
//A{id=999}
//他们的地址都不一样
//cn.设计模式.原型模式.A@6d311334
//cn.设计模式.原型模式.A@682a0b20
//cn.设计模式.原型模式.A@3d075dc0
//cn.设计模式.原型模式.A@214c265e
//cn.设计模式.原型模式.A@448139f0
代理模式
静态代理
public interface USB {
public Integer sale();
}
public interface Computer {
public Integer sale();
}
public class USB_Factory implements USB{
@Override
public Integer sale() {
System.out.println("工厂批发USB:50元/个");
return 50;
}
}
public class Computer_Factory implements Computer{
@Override
public Integer sale() {
System.out.println("工厂批发Computer:2000元/个");
return 2000;
}
}
public class Pro implements USB,Computer{
private USB_Factory usb_factory;
private Computer_Factory computer_factory;
public Pro(Object object){
if(object instanceof USB_Factory){
this.usb_factory = (USB_Factory) object;
}
if(object instanceof Computer_Factory){
this.computer_factory = (Computer_Factory) object;
}
}
@Override
public Integer sale() {
Integer price = computer_factory.sale();
//Integer price = usb_factory.sale();
System.out.println("代理商:"+(price*2)+"元/个");
System.out.println("还提供一年免修");
return price*2;
}
}
public class Test {
public static void main(String[] args) {
Computer computer = new Pro(new Computer_Factory());
//USB usb = new Pro(new USB_Factory());
Integer price = computer.sale();
//Integer price = usb.sale();
System.out.println("我买到的价钱是:"+price+"元/个");
}
}
//USB
//工厂批发USB:50元/个
//代理商:100元/个
//还提供一年免修
//我买到的价钱是:100元/个
//Computer
//工厂批发Computer:2000元/个
//代理商:4000元/个
//还提供一年免修
//我买到的价钱是:4000元/个
动态代理
public interface USB {
public Integer sale();
}
public interface Computer {
public Integer sale();
}
public class USB_Factory implements USB{
@Override
public Integer sale() {
System.out.println("工厂批发USB:50元/个");
return 50;
}
}
public class Computer_Factory implements Computer{
@Override
public Integer sale() {
System.out.println("工厂批发Computer:2000元/个");
return 2000;
}
}
public class Handler implements InvocationHandler {
private Object object;
public Handler(Object object){
this.object = object;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
Integer price = (Integer) method.invoke(object,args);
System.out.println("代理商:"+(price*2)+"元/个");
System.out.println("还提供一年免修");
return price*2;
}
}
public class Test {
public static void main(String[] args) {
//Object object = new Computer_Factory();
Object object = new USB_Factory();
Handler handler = new Handler(object);
Object proxy = Proxy.newProxyInstance(object.getClass().getClassLoader(), object.getClass().getInterfaces(), handler);
//Integer price = ((Computer).proxy).sale();
Integer price = ((USB) proxy).sale();
System.out.println("我买到的价钱是:"+price+"元/个");
}
}
//USB
//工厂批发USB:50元/个
//代理商:100元/个
//还提供一年免修
//我买到的价钱是:100元/个
//Computer:
//工厂批发Computer:2000元/个
//代理商:4000元/个
//还提供一年免修
//我买到的价钱是:4000元/个
适配器模式
public class Functions {
public void add(Integer a){
System.out.println("add:"+a);
}
public void del(Integer b){
System.out.println("del:"+b);
}
}
public interface FN {
void add(Integer i);
void del(Integer...args);
}
public class Adapter implements FN{
private Functions functions;
public Adapter(Functions functions){
this.functions = functions;
}
@Override
public void add(Integer i) {
functions.add(i);
}
@Override
public void del(Integer... args) {
for (Integer a:args) {
functions.del(a);
}
}
}
//Component需要FN接口才能工作,但是现在只提供Functions类
//现在需要用Functions类的方法来处理FN接口的方法---适配器解决
public class Component{
public void fun(FN fn){
fn.add(5);
fn.del(6,7,8);
}
}
public class Test {
public static void main(String[] args) {
Component component = new Component();
component.fun(new Adapter(new Functions()));
}
}
//add:5
//del:6
//del:7
//del:8
策略模式
public class A {
public void fun(B b){
System.out.println("第一步");
System.out.println("第二步");
//第三步是缺口,需要外界提供
b.exec();
System.out.println("第四步");
System.out.println("第五步");
}
}
public interface B {
void exec();
}
public class Test {
public static void main(String[] args) {
B b = ()-> {
System.out.println("这是外界提供的第三步");
};
new A().fun(b);
}
}
//第一步
//第二步
//这是外界提供的第三步
//第四步
//第五步
装饰模式
public interface Person {
public void work();
}
public class Student implements Person{
@Override
public void work() {
System.out.println("学生在学习");
}
}
public abstract class Decorator implements Person{
protected Person person;
public Decorator(Person person){
this.person = person;
}
public void work(){
person.work();
}
}
public class Singer extends Decorator{
public Singer(Person person) {
super(person);
}
public void work(){
System.out.print("爱唱歌的");
super.work();
}
}
public class Dancer extends Decorator{
public Dancer(Person person) {
super(person);
}
public void work(){
System.out.print("爱跳舞的");
super.work();
}
}
public class Test {
public static void main(String[] args) {
Person person = new Dancer(new Singer(new Dancer(new Singer(new Dancer(new Student())))));
person.work();
}
}
//爱跳舞的爱唱歌的爱跳舞的爱唱歌的爱跳舞的学生在学习
责任链模式
例子:请假,< 1,组长批,< 3,PM批,否则:Leader批
public abstract class Handler {
protected Handler nextHandler;
public Handler(Handler nexthandler){
this.nextHandler = nexthandler;
}
public Handler(){
}
public abstract void handle(int days);
}
public class TeamLeader extends Handler{
public TeamLeader(Handler nextHandler){
super(nextHandler);
}
public TeamLeader(){
}
@Override
public void handle(int days) {
System.out.println("TeamLeader同意");
if(days>1){
nextHandler.handle(days);
}
}
}
public class PM extends Handler{
public PM(Handler nextHandler){
super(nextHandler);
}
public PM(){
}
@Override
public void handle(int days) {
System.out.println("PM同意");
if(days>3){
nextHandler.handle(days);
}
}
}
public class Leader extends Handler{
public Leader(Handler nextHandler){
super(nextHandler);
}
public Leader(){
}
@Override
public void handle(int days) {
System.out.println("Leader同意");
}
}
public class Test {
public static void main(String[] args) {
new TeamLeader(new PM(new Leader())).handle(7);
}
}
//days=7:
//TeamLeader同意
//PM同意
//Leader同意
//days=2:
//TeamLeader同意
//PM同意
//days=1:
//TeamLeader同意
观察者模式
例子:涨价、降价
public abstract class Subject {
//放观察者们
private Set<Observer> observerSet = new HashSet<>();
public void addObserver(Observer observer){
observerSet.add(observer);
}
public void deleteObserver(Observer observer){
observerSet.remove(observer);
}
/**
* 将本目标对象的变化通知所有的观察者
* @param arg
*/
protected void notifyAllObservers(Object arg){
for(Observer ob : observerSet){
ob.update(arg);
}
}
}
public class Goods extends Subject{
private double price;
public Goods(double price){
this.price = price;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
double dPrice = price - this.price;//价格变化
this.price = price;
if(Math.abs(dPrice)>0.5){
this.notifyAllObservers(dPrice);
}
}
}
public interface Observer {
/**
* 该方法表示当本观察者所观察的目标对象发生变化时,执行的逻辑,
* 该方法的参数抽象地表示目标对象的变化
* 该方法将由目标对象调用(观察者会添加到目标对象上)
* @param arg
*/
public void update(Object arg);
}
public class Customer implements Observer{
@Override
public void update(Object arg) {
double dPrice = (Double) arg;
if(dPrice > 0){
System.out.println("消费者:涨价了,哭泣");
}else{
System.out.println("消费者:降价了,开心");
}
}
}
public class Manager implements Observer{
@Override
public void update(Object arg) {
double dPrice = (Double) arg;
if(Math.abs(dPrice)<5){
System.out.println("监管者:价格基本平稳。");
}else{
System.out.println("监管者:价格波动有点大。");
}
}
}
public class Provider implements Observer{
@Override
public void update(Object arg) {
double dPrice = (Double) arg;
if(dPrice > 0){
System.out.println("供应商:涨价了,开心");
}else{
System.out.println("供应商:跌价了,哭泣");
}
}
}
public class Test {
public static void main(String[] args) {
Goods goods = new Goods(100);
goods.addObserver(new Customer());
goods.addObserver(new Provider());
goods.addObserver(new Manager());
goods.setPrice(103);
goods.setPrice(112);
goods.setPrice(109);
}
}
//供应商:涨价了,开心
//消费者:涨价了,哭泣
//监管者:价格基本平稳。
//供应商:涨价了,开心
//消费者:涨价了,哭泣
//监管者:价格波动有点大。
//供应商:跌价了,哭泣
//消费者:降价了,开心
//监管者:价格基本平稳。