Design Pattern (1) Factory pattern

Source: Internet
Author: User

Agile Software Development-principles, models and practices

The dependency inversion principle (DIP) describes that all classes should depend on abstract classes to avoid dependency on specific classes.

Circle c = new Circle (r );

Circle is a specific class, so the forces that create Circle violate DIP. Many specific classes are

It is very easy to change, depending on them, it will cause problems. This uses the Factory mode and the factory mode.

Instances of specific objects can be created only by relying on abstract interfaces.

The following is a specific example.

// Client. java

Package com. factory;
Import static org. junit. Assert .*;
Import org. junit. Test;
Public class Client {
@ Test
Public void testFactory (){
ShapeFactory sf = new ShapeFactoryImpl ();
Shape s = sf. make ("Circle ");
AssertTrue (s instanceof Circle );
}
}

// ShapeFactory. java

Package com. factory;
Public interface ShapeFactory {
Shape make (String shapeName );
}

// Shape. java

Package com. factory;
Public abstract class Shape {
}

// Circle. java

Package com. factory;
Public class Circle extends Shape {
}

// ShapeFactoryImpl. java

Package com. factory;
Public class ShapeFactoryImpl implements ShapeFactory {
@ Override
Public Shape make (String shapeName ){
If (shapeName. equals ("Circle ")){
Return new Circle ();
} Else {
Return null;
}
}
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.