Java六大常用设计模式

单例模式

就是一个应用程序中,某个类的实例对象只有一个,你没有办法去new,因为构造器是被private修饰的,一般通过getInstance()的方法来获取它们的实例
饿汉式写法

public class Singleton {  
   private static Singleton instance = new Singleton();  
   private Singleton (){}  
   public static Singleton getInstance() {  
   return instance;  
   }  
}

懒汉式写法(线程安全)

public class Singleton {  
   private static Singleton instance;  
   private Singleton (){}  
   public static synchronized Singleton getInstance() {  
   if (instance == null) {  
       instance = new Singleton();  
   }  
   return instance;  
   }  
}

静态内部类

public class Singleton {  
   private static class SingletonHolder {  
   private static final Singleton INSTANCE = new Singleton();  
   }  
   private Singleton (){}  
   public static final Singleton getInstance() {  
   return SingletonHolder.INSTANCE;  
   }  
}

观察者模式

对象间一对多的依赖关系,当一个对象的状态发生改变时,所有依赖于它的对象都得到通知并被自动更新
情景:小王和小李喜欢小美,时刻关注着她的行为

public interface Person {
   //小王和小李通过这个接口可以接收到小美发过来的消息
   void getMessage(String s);
}
public class LaoWang implements Person {

   private String name = "小王";

   public LaoWang() {
   }

   @Override
   public void getMessage(String s) {
       System.out.println(name + "接到了小美打过来的电话,电话内容是:" + s);
   }

}

public class LaoLi implements Person {

   private String name = "小李";

   public LaoLi() {
   }

   @Override
   public void getMessage(String s) {
       System.out.println(name + "接到了小美打过来的电话,电话内容是:->" + s);
   }

}
public class XiaoMei {
   List<Person> list = new ArrayList<Person>();
    public XiaoMei(){
    }
//把所有暗恋者加进来
    public void addPerson(Person person){
        list.add(person);
    }

    //遍历list,把自己的通知发送给所有暗恋自己的人
    public void notifyPerson() {
        for(Person person:list){
            person.getMessage("你们过来吧,谁先过来谁就能陪我一起玩儿游戏!");
        }
    }
}

装饰者模式

对已有的业务逻辑进一步的封装,使其增加额外的功能,如Java中的IO流就使用了装饰者模式,用户在使用的时候,可以任意组装,达到自己想要的效果

public class Food {

   private String food_name;

   public Food() {
   }

   public Food(String food_name) {
       this.food_name = food_name;
   }

   public String make() {
       return food_name;
   };
}
//面包类
public class Bread extends Food {

   private Food basic_food;

   public Bread(Food basic_food) {
       this.basic_food = basic_food;
   }

   public String make() {
       return basic_food.make()+"+面包";
   }
}

//奶油类
public class Cream extends Food {

   private Food basic_food;

   public Cream(Food basic_food) {
       this.basic_food = basic_food;
   }

   public String make() {
       return basic_food.make()+"+奶油";
   }
}

//蔬菜类
public class Vegetable extends Food {

   private Food basic_food;

   public Vegetable(Food basic_food) {
       this.basic_food = basic_food;
   }

   public String make() {
       return basic_food.make()+"+蔬菜";
   }

}
public class Test {
   public static void main(String[] args) {
       Food food = new Bread(new Vegetable(new Cream(new Food("香肠"))));
       System.out.println(food.make());
   }
}

工厂模式

简单工厂模式:一个抽象的接口,多个抽象接口的实现类,一个工厂类,用来实例化抽象的接口

// 抽象产品类
abstract class Car {
   public void run();

   public void stop();
}

// 具体实现类
class Benz implements Car {
   public void run() {
       System.out.println("Benz开始启动了。。。。。");
   }

   public void stop() {
       System.out.println("Benz停车了。。。。。");
   }
}

class Ford implements Car {
   public void run() {
       System.out.println("Ford开始启动了。。。");
   }

   public void stop() {
       System.out.println("Ford停车了。。。。");
   }
}

// 工厂类
class Factory {
   public static Car getCarInstance(String type) {
       Car c = null;
       if ("Benz".equals(type)) {
           c = new Benz();
       }
       if ("Ford".equals(type)) {
           c = new Ford();
       }
       return c;
   }
}

public class Test {

   public static void main(String[] args) {
       Car c = Factory.getCarInstance("Benz");
       if (c != null) {
           c.run();
           c.stop();
       } else {
           System.out.println("造不了这种汽车。。。");
       }

   }

}

工厂方法模式:由抽象工厂的子类去实例化产品

 

// 抽象产品角色
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();
   }
}

抽象工厂模式:与工厂方法模式不同的是,工厂方法模式中的工厂只生产单一的产品,而抽象工厂模式中的工厂生产多个产品

/抽象工厂类
public abstract class AbstractFactory {
   public abstract Vehicle createVehicle();
   public abstract Weapon createWeapon();
   public abstract Food createFood();
}
//具体工厂类,其中Food,Vehicle,Weapon是抽象类,
public class DefaultFactory extends AbstractFactory{
   @Override
   public Food createFood() {
       return new Apple();
   }
   @Override
   public Vehicle createVehicle() {
       return new Car();
   }
   @Override
   public Weapon createWeapon() {
       return new AK47();
   }
}
//测试类
public class Test {
   public static void main(String[] args) {
       AbstractFactory f = new DefaultFactory();
       Vehicle v = f.createVehicle();
       v.run();
       Weapon w = f.createWeapon();
       w.shoot();
       Food a = f.createFood();
       a.printName();
   }
}

生产者/消费者模式

某个模块负责产生数据,这些数据由另一个模块来负责处理,产生数据的模块,就形象地称为生产者;而处理数据的模块,就称为消费者。在生产者与消费者之间在加个缓冲区,我们形象的称之为仓库,生产者负责往仓库了进商品,而消费者负责从仓库里拿商品,这就构成了生产者消费者模式

//此类是共享数据区域
public class SyncStack {
    
    private String[]  str = new String[10];
    
    private int index;
    
    //供生产者调用
    public synchronized void push(String sst){
        if(index == sst.length()){
            try {
                wait();
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        this.notify();//唤醒在此对象监视器上等待的单个线程 
        str[index] = sst;
        index++;
    }
    
    //供消费者调用  
    public synchronized String pop(){
        if(index == 0){
            try {
                wait();
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        this.notify();
        index--;
        String product = str[index];
        return product;
        
    }
    
    //就是定义一个返回值为数组的方法,返回的是一个String[]引用  
    public String[] pro(){
        return str;
    }
}
public class Producter implements Runnable {
    //创建生产者
    private SyncStack stack;
    
    public Producter(SyncStack stack){
        this.stack = stack;
    }
    
    public void run(){
        for(int i = 0;i<stack.pro().length;i++){
            String producter = "产品" + i;
            stack.push(producter);
            System.out.println("生产了:" + producter);
            try {
                Thread.sleep(200);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            
        }
    }
}
public class Consumer implements Runnable {
    //创建消费者
    private SyncStack stack;
    
    public Consumer(SyncStack stack){
        this.stack = stack;
    }
    public void run(){
        for(int i=0;i<stack.pro().length;i++){
            String consumer = stack.pop();
            System.out.println("消费了:" + consumer );
            
            try {
                Thread.sleep(400);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
}
public class TestDeam {
//测试类
    public static void main(String[] args) {
        SyncStack stack = new SyncStack();  
        Consumer p = new Consumer(stack);  
        Producter c = new Producter(stack);  
             
        new Thread(p).start();  
        new Thread(c).start(); 

    }
}

代理模式

//代理接口
public interface ProxyInterface {
//需要代理的是结婚这件事,如果还有其他事情需要代理
void marry();
}
public class WeddingCompany implements ProxyInterface {

private ProxyInterface proxyInterface;

public WeddingCompany(ProxyInterface proxyInterface) {
 this.proxyInterface = proxyInterface;
}

@Override
public void marry() {
 System.out.println("我们是婚庆公司的");
 System.out.println("我们在做结婚前的准备工作");
 System.out.println("可以开始结婚了");
 proxyInterface.marry();
}

}
public class NormalHome implements ProxyInterface{

@Override
public void marry() {
 System.out.println("我们结婚啦~");
}

}
public class Test {
public static void main(String[] args) {
 ProxyInterface proxyInterface = new WeddingCompany(new NormalHome());
 proxyInterface.marry();
}
}

猜你喜欢

转载自blog.csdn.net/qq_45485851/article/details/105456721