Common design patterns in android

Singleton mode

  • Ensure that a class has only one instance and that it instantiates itself and provides this instance to the entire system.
public class Singleton {
    private static volatile Singleton instance = null;

    private Singleton(){
    }

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

Build mode

  • Separating the construction of a complex object from its representation allows the same construction process to create different representations
    Suppose we have a Person class that we use to build a large number of people. There are many attributes in this Person class, the most common of which are name, age, weight, height s, and so on, and we allow these values to not be set, then we will need to overload a lot of construction methods.

Person adds a static internal class Builder class and modifies the constructor of the Person class with the following code.

public class Person {
    private String name;
    private int age;
    private double height;
    private double weight;

    privatePerson(Builder builder) {
        this.name=builder.name;
        this.age=builder.age;
        this.height=builder.height;
        this.weight=builder.weight;
    }
    public String getName() {
        return name;
    }

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

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public double getHeight() {
        return height;
    }

    public void setHeight(double height) {
        this.height = height;
    }

    public double getWeight() {
        return weight;
    }

    public void setWeight(double weight) {
        this.weight = weight;
    }

    static class Builder{
        private String name;
        private int age;
        private double height;
        private double weight;
        public Builder name(String name){
            this.name=name;
            return this;
        }
        public Builder age(int age){
            this.age=age;
            return this;
        }
        public Builder height(double height){
            this.height=height;
            return this;
        }

        public Builder weight(double weight){
            this.weight=weight;
            return this;
        }

        public Person build(){
            return new Person(this);
        }
    }
}

When creating a person object

Person.Builder builder=new Person.Builder();
Person person=builder
        .name("Zhang San")
        .age(18)
        .height(178.5)
        .weight(67.4)
        .build();

Common AlertDialog, OkHttp, etc. use build mode

Observer mode

  • Defines a one-to-many dependency between objects. When an object's state changes, all objects that depend on it are notified and automatically updated
public class Observable<T> {
    List<Observer<T>> mObservers = new ArrayList<Observer<T>>();

    public void register(Observer<T> observer) {
        if (observer == null) {
            throw new NullPointerException("observer == null");
        }
        synchronized (this) {
            if (!mObservers.contains(observer))
                mObservers.add(observer);
        }
    }

    public synchronized void unregister(Observer<T> observer) {
        mObservers.remove(observer);
    }

    public void notifyObservers(T data) {
        for (Observer<T> observer : mObservers) {
            observer.onUpdate(this, data);
        }
    }

}

Define an interface

public interface Observer<T> {
    void onUpdate(Observable<T> observable,T data);
}

usage

public class Main {
    public static void main(String [] args){
        Observable<String> observable=new Observable<String>();
        Observer<String> observer1=new Observer<String>() {
            @Override
            public void onUpdate(Observable<String> observable, String data) {
                System.out.println("Observer 1:"+data);
            }
        };
        Observer<String> observer2=new Observer<String>() {
            @Override
            public void onUpdate(Observable<String> observable, String data) {
                System.out.println("Observer 2:"+data);
            }
        };

        observable.register(observer1);
        observable.register(observer2);



        observable.notifyObservers("Publish message 1");
        observable.notifyObservers("Publish Message 2");

        observable.unregister(observer1);

        observable.notifyObservers("Publish Message 3");

    }
}

EventBus

EventBus.getDefault().register(Object subscriber);
EventBus.getDefault().unregister(Object subscriber);

EventBus.getDefault().post(Object event);

RxJava

Observable<String> myObservable = Observable.create(  
    new Observable.OnSubscribe<String>() {  
        @Override  
        public void call(Subscriber<? super String> sub) {  
            sub.onNext("Hello, world!");  
            sub.onCompleted();  
        }  
    }  
);
Subscriber<String> mySubscriber = new Subscriber<String>() {  
    @Override  
    public void onNext(String s) { System.out.println(s); }  

    @Override  
    public void onCompleted() { }  

    @Override  
    public void onError(Throwable e) { }  
};

myObservable.subscribe(mySubscriber);

Prototype mode

Specify the kind of objects created with prototype instances and create new objects by copying them.

First we define a Person class to implement the Cloneable interface override clone method

public class Person implements Cloneable {

    private String name;
    private String age;
    private String gender;


    public String getName() {
        return name;
    }

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

    public String getAge() {
        return age;
    }

    public void setAge(String age) {
        this.age = age;
    }

    public String getGender() {
        return gender;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }

    @Override
    protected Object clone() {
        Person person=null;
        try {
            person=(Person)super.clone();
            person.name=this.name;
            person.age=this.age;
            person.gender=this.gender;
        } catch (CloneNotSupportedException e) {
            e.printStackTrace();
        }
        return person;
    }
}
        Person person = new Person();
        person.setAge("20");
        person.setGender("male");
        person.setName("Advocate");
        Person person1 = (Person) person.clone();

At this point person and person1 have the same content but different memory pointing

proxy pattern

Provides a new object for manipulating or replacing a real object.

A Find intermediary rental for Demo to build proxy mode, first define an abstract theme, IHouse

public interface IHouse {  
    void getHouseInfo();  
    void signContract();  
    void payFees();  
}  

Define Real Theme

public class House implements IHouse{  
    private final String TAG = House.class.getSimpleName();  
    private String name;  
    private double price;  

    public House(String name, double price){  
        this.name = name;  
        this.price = price;  
    }  

    @Override  
    public void getHouseInfo() {  
        Log.i(TAG, "House Info- name:" + name + "  ¥:" + price);  
    }  

    @Override  
    public void signContract() {  
        Log.i(TAG, "Contract:" + name + "  signed at" +  
               new SimpleDateFormat("HH:mm:ss").format(SystemClock.uptimeMillis()));  
    }  

    @Override  
    public void payFees() {  
        Log.i(TAG, "Bill: name-" + name + "  $-" + price);  
    }  
}  

Define a housing agent and also implement the IHouse interface

public class ProxyHouse implements IHouse{  
    private final String TAG = ProxyHouse.class.getSimpleName();  
    private IHouse house;  
    public ProxyHouse(IHouse house){  
        this.house = house;  
    }  
    @Override  
    public void getHouseInfo() {  
        Log.i(TAG, "searching");  
        house.getHouseInfo();  
        Log.i(TAG, "search finished");  
    }  

    @Override  
    public void signContract() {  
        Log.i(TAG, "prepare contract");  
        house.signContract();  
    }  

    @Override  
    public void payFees() {  
        house.payFees();  
    }  
}  

For customers, you don't have to interact directly with the House at all, but with the proxy

IHouse house = new House("Downton Abbey", 5000);  
IHouse proxyHouse = new ProxyHouse(house);  
Log.i(TAG, "looking for a perfect house");  
proxyHouse.getHouseInfo();  
Log.i(TAG, "thinking");  
proxyHouse.signContract();  
proxyHouse.payFees();  
Log.i(TAG, "so easy");  

Factory Mode

1. Factory Method
2. Abstract Factory

Mobile phones with different operating systems manufactured in factories as an example

public interface Phone {  
    public void getOS();  
}  

Android,IOS and two mobile phones are implemented according to the Phone interface.

public class AndroidPhone implements Phone {  
    private final String TAG = AndroidPhone.class.getSimpleName();  
    @Override  
    public void getOS() {  
        Log.i(TAG, "im Android");  
    }  
}  
public class IosPhone implements Phone {  
    private final String TAG = IosPhone.class.getSimpleName();  
    @Override  
    public void getOS() {  
        Log.i(TAG, "im IOS");  
    }  
}  

Standard factory method patterns require Abstract Factory interfaces or base classes.

public abstract class IGenerator {  
    public abstract IPhone generatePhone() throws Exception;  
}  
public class AndroidGenerator extends IGenerator {  
    @Override  
    public Phone generatePhone() {  
        return new AndroidPhone();  
    }  
}  
public class IOSGenerator extends IGenerator {  
    @Override  
    public Phone generatePhone() {  
        return new IosPhone();  
    }  

production

AndroidGenerator androidGenerator = new AndroidGenerator();  
IOSGenerator iosGenerator = new IOSGenerator();  

AndroidPhone android = androidGenerator.generatePhone();  
IosPhone ios = iosGenerator.generatePhone();  

Keywords: Android iOS Mobile OkHttp

Added by dirkadirka on Sat, 29 Jun 2019 19:49:31 +0300