프로토 타입 모델 : (05)에 설명 된 자바 디자인 패턴

I. 서론 프로토 타입 모델

1, 기본 개념

프로토 타입 모델은 스키마 객체를 생성 속한다. 복사와 프로토 타입 객체 접근 방식을 개체의 동일한 유형의 이상을 생성 한 후 프로토 타입 객체를 제공하여 생성 된 모든 객체의 유형을 표시하고합니다.

2 모드 구조

모드는 프로토 타입 객체 구현 "복제"자신의 인터페이스 할 수있다 필요, 그래서 당신은 개체 자체를 복사하여 예제의 새로운 인스턴스를 생성 할 수 있습니다. 이 방법은 복제 자체를 달성하기로 이러한 방식으로, 원형 인스턴스를 통해 새로운 객체를 생성, 더 이상 새를 만드는 통해 갈 필요없이,이 방법으로 새 ​​개체를 얻을 수있는만큼, 인스턴스 자체의이 유형에 대해 신경 쓸 필요가 없다 .

3, 코드 구현

1) UML 다이어그램

프로토 타입 모드 : (05)에 설명 된 자바 디자인 패턴
2), 중심적인 역할

이 양식은 세 가지 역할에 관한 것이다

1) 고객 (클라이언트) 역할 : 클라이언트 요청은 클래스의 객체를 생성 할 수 있습니다.

2) 추상적 인 원형 (프로토 타입) 역할 : 이것은 일반적으로 Java 인터페이스 또는 Java 추상 클래스에 의해 구현하는 추상 역할이다. 이 역할은 모든 필요한 특정 프로토 타입 클래스 인터페이스를 제공합니다.

3) 특정 프로토 타입 (콘크리트 프로토 타입) 역할 : 개체가 복사됩니다. 이 역할은 인터페이스 추상적 인 프로토 타입 역할을 필요로 구현해야합니다.

3) JDK 소스 코드에 기초하여 달성

/**
 * 基于JDK源码方式实现原型模式
 */
public class C01_Property {
    public static void main(String[] args) {
        Product product = new Product("机械键盘","白色",100.00) ;
        Product product1 = (Product) product.clone();
        Product product2 = (Product) product.clone();
        System.out.println(product1);
        System.out.println(product2);
        System.out.println(product1==product2);  // false
    }
}
class Product implements Cloneable {
    private String name ;
    private String color ;
    private Double price ;
    public Product(String name, String color, Double price) {
        this.name = name;
        this.color = color;
        this.price = price;
    }
    @Override
    public String toString() {
        return "Product{" +
                "name='" + name + '\'' +
                ", color='" + color + '\'' +
                ", price=" + price +
                '}';
    }
    @Override
    protected Object clone() {
        Product product = null ;
        try{
            product = (Product)super.clone() ;
        } catch (Exception e){
            e.printStackTrace();
        }
        return product ;
    }
    // 省略GET和SET方法
}

두, 스프링 프레임 워크 응용 프로그램

1, 구성 파일

<!-- 多例Bean -->
<bean id="sheep01" class="com.model.design.spring.node05.property.Sheep" scope="prototype" />
<!-- 单例Bean 默认: scope="singleton" -->
<bean id="sheep02" class="com.model.design.spring.node05.property.Sheep"/>

2 테스트 블록

@Test
public void test01 (){
    ApplicationContext context01 = new ClassPathXmlApplicationContext(
            "/spring/spring-property.xml");
    // 原型模式
    Sheep sheep1 = (Sheep)context01.getBean("sheep01") ;
    Sheep sheep2 = (Sheep)context01.getBean("sheep01") ;
    System.out.println(sheep1==sheep2); // false
    // 单例模式
    Sheep sheep3 = (Sheep)context01.getBean("sheep02") ;
    Sheep sheep4 = (Sheep)context01.getBean("sheep02") ;
    System.out.println(sheep3==sheep4); // true
}

(3) 코어 소스 코드

  • 어디 클래스 : org.springframework.beans.factory.support.AbstractBeanFactory
  • 어디 방법 : doGetBean

1) 구현 방법

if (mbd.isSingleton()) {
    sharedInstance = this.getSingleton(beanName, new ObjectFactory<Object>() {
        public Object getObject() throws BeansException {
            try {
                return AbstractBeanFactory.this.createBean(beanName, mbd, args);
            } catch (BeansException var2) {
                AbstractBeanFactory.this.destroySingleton(beanName);
                throw var2;
            }
        }
    });
    bean = this.getObjectForBeanInstance(sharedInstance, name, beanName, mbd);
} else if (mbd.isPrototype()) {
    var11 = null;
    Object prototypeInstance;
    try {
        this.beforePrototypeCreation(beanName);
        prototypeInstance = this.createBean(beanName, mbd, args);
    } finally {
        this.afterPrototypeCreation(beanName);
    }
    bean = this.getObjectForBeanInstance(prototypeInstance, name, beanName, mbd);
} 

판정 2) 경우 싱글

그래서 기본 모드 [범위 = "프로토 타입"] 지정된 하나의 실시 예에서, 원형 모형이다.

public boolean isSingleton() {
    return "singleton".equals(this.scope) || "".equals(this.scope);
}
public boolean isPrototype() {
    return "prototype".equals(this.scope);
}

복사 셋째, 깊이

1, 얕은 사본

1) 데이터 타입은 기본 데이터 형식 문자열 타입 부재 직접 단순 복사본 전송 변수 값, 즉 새로운 복사 대상의 특성 값이다.
2) 데이터 형식은 데이터의 참조 형 멤버 변수, 예를 들면 변수의 멤버는 새로운 복사본 유일한 멤버 변수 기준값 인 기준 단순 복사본 (메모리 어드레스)에 의해 전달되는 배열 객체 클래스 등이며 객체. 실제로 두 객체의 멤버 변수가 동일한 인스턴스를 가리. 객체가 다른 객체의 속성에 영향을 미치는 속성을 수정합니다.
3) 단순 복사본을 기본 클론 () 메소드를 사용하여 수행됩니다.

2, 전체 복사

1) 개념을 설명

값을 단순 복사본을 복사 이외에 복사는 또한 데이터 참조 타입에 대한 책임이있다. 다른 개체를 참조하는 변수가 참조하는 원래의 객체가,이 간접 재생 호출되는 객체의 복사본에 대한 참조입니다보다는, 복사 새 개체를 가리 킵니다.

2) 소스 코드를 달성

깊은 복제 시퀀스의 실현

스트림에 객체 직렬화 (직렬화) 프로세스의 과정에, 그리고 객체 직렬화 복원 (직렬화) 과정이라고 스트림 과정에서 판독한다. 스트림 개체의 복사본이고 원본 개체가 여전히 내부 JVM에 존재 쓴 주목해야한다.

깊은 복제 객체에서 자바 언어에서 객체는 종종 (직렬화) 스트림에서 다시 읽어 후 Serializable 인터페이스, 다음 개체 (개체의 실제 전용 복사본) 스트림 (직렬화)에 기록을 확인하고 달성 할 수있다 , 당신은 객체를 재구성 할 수 있습니다.

/**
 * 深拷贝和浅拷贝对比案例
 */
public class C02_DeepClone {
    public static void main(String[] args) throws Exception {
        Dog dog = new Dog("Tom") ;
        Dog dog1 = (Dog)dog.clone() ;
        Dog dog2 = (Dog)dog.clone() ;
        // dog1:1639622804;dog2:1639622804
        System.out.println("dog1:"+dog1.cat.hashCode()+";dog2:"+dog2.cat.hashCode());
        Dog dog3 = (Dog)dog.deepClone() ;
        Dog dog4 = (Dog)dog.deepClone() ;
        // dog3:1937348256;dog4:1641808846
        System.out.println("dog3:"+dog3.cat.hashCode()+";dog4:"+dog4.cat.hashCode());
    }
}

class Cat implements Serializable {
    public String name ;
    public Cat (String name){
        this.name = name ;
    }
}
class Dog implements Cloneable,Serializable {
    public String name ;
    public Cat cat ;
    public Dog (String name){
        this.name = name ;
        this.cat = new Cat("Kit") ;
    }
    @Override
    protected Object clone() {
        Dog dog = null ;
        try{
            dog = (Dog)super.clone() ;
        } catch (Exception e){
            e.printStackTrace();
        }
        return dog ;
    }
    public Object deepClone() throws IOException, ClassNotFoundException{
        //将对象写到流里面:序列化
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        ObjectOutputStream oos = new ObjectOutputStream(bos);
        oos.writeObject(this);
        //从流里面读出对象:反序列化
        ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
        ObjectInputStream ois = new ObjectInputStream(bis);
        return ois.readObject();
    }
}

넷째, 장점과 요약의 단점

1 장점을 요약

프로토 타입 모드는 실행시에 동적으로 변화하는 특정 유형의 실현을 할 수 있습니다. 운전 중 프로토 타입 모드는, 구현 형 프로토 타입의 인터페이스에 맞춰 등록하는 고객, 동적 거기 인터페이스에 변화가 없지만, 사실 이미 클래스의 다른 인스턴스를 실행하는 것, 특정 구현 유형을 변경할 수 있습니다. 클론은 클래스 인스턴스의 프로토 타입과 유사하기 때문에.

2, 단점 요약

프로토 타입 모델의 주요 단점은 각 클래스가 복제 방법으로 장착해야한다는 것입니다. 복제 방법은 기능 클래스는이 새로운 클래스는 어렵지 않습니다를 들어, 고려,하지만 클래스는 간접 객체의 참조 순서, 또는 참조를 지원하지 않습니다 특히, 매우 쉽지 않을 수있는 몇 가지 수업을하기 위해 필요로 시 클릭 구조를 포함.

다섯째, 소스 코드의 주소

GitHub地址:知了一笑
https://github.com/cicadasmile/model-arithmetic-parent
码云地址:知了一笑
https://gitee.com/cicadasmile/model-arithmetic-parent


추천

출처www.cnblogs.com/cicada-smile/p/11261575.html