In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-27 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly introduces "how to use the decoration mode in java". In the daily operation, I believe that many people have doubts about how to use the decoration mode in java. The editor consulted all kinds of materials and sorted out simple and easy-to-use operation methods. I hope it will be helpful to answer the doubts about "how to use the decoration mode in java". Next, please follow the editor to study!
1. Definition of pattern
How to achieve flexible bonus calculation? Suppose the bonus is calculated as follows:
Monthly business bonus for each person: sales for the month * 3%
Cumulative bonus for each person: total rebate amount * 0.1%
Team bonus: total team sales * 1%
Problems in bonus calculation:
1. The calculation logic is complex.
two。 To be flexible, you can easily add or decrease functions
3. Dynamic combinatorial computing, different people participate in different calculations
Abstract question: how can we transparently add functions to an object and realize the dynamic combination of functions?
Definition of Decoration pattern:
Add some additional responsibilities to an object dynamically, and decorating patterns are more flexible than generating subclasses in terms of adding functionality.
2. UML diagram
Component: interfaces to component objects to which responsibilities can be dynamically added
ConcreteComponent: a specific component object that implements the component interface, usually the original object decorated by the decorator, that is, you can add responsibilities to this object
Decorator: the abstract parent class of all decorators needs to define an interface consistent with the component interface and hold a Component object, which is actually holding a decorated object
ConcreteDecorator: a specific decorator object that implements the specific functions to be added to the decorated object
Code:
/ * *
* simulate the database in memory and prepare some test data to calculate the bonus
* / public class TempDB {
Private TempDB () {} / * *
* record everyone's monthly sales, using only personnel, the month is useless
, /
Public static Map mapMonthSaleMoney = new HashMap (); static {/ / populate the test data
MapMonthSaleMoney.put (Zhang San, 10000.0)
MapMonthSaleMoney.put (Li Si, 20000.0)
MapMonthSaleMoney.put (Wang Wu, 30000.0)
}
} / * *
* component interface for calculating bonus
* / public abstract class Component {
/ * *
* calculate someone's bonus for a certain period of time, some parameters will not be used in the demonstration
* but it will be used in the actual business implementation, in order to show that this is a specific business method
* so these parameters are retained
* @ param user the person whose bonus is calculated
* @ param begin the start time of the bonus calculation
* @ param end the end time of the bonus calculation
* @ return someone's bonus for a certain period of time
, /
Public abstract double calcPrize (String user,Date begin,Date end)
} / * *
* the basic class that calculates the bonus is also the object decorated by the decorator
* / public class ConcreteComponent extends Component {
Public double calcPrize (String user, Date begin, Date end) {/ / is just a default implementation with no bonus by default
Return 0
}
} / * *
* the interface of the decorator needs to implement the same interface as the decorated object
* / public abstract class Decorator extends Component {
/ * *
* hold the decorated component object
, /
Protected Component c; / * *
* pass in the decorated object through the construction method
* @ param c objects to be decorated
, /
Public Decorator (Component c) {this.c = c
} public double calcPrize (String user, Date begin, Date end) {/ / methods for transferring component objects
Return c.calcPrize (user, begin, end)
}
} / * *
* decorator object to calculate the current month's business bonus
* / public class MonthPrizeDecorator extends Decorator {
Public MonthPrizeDecorator (Component c) {super (c)
} public double calcPrize (String user, Date begin, Date end) {/ / 1: get the bonus calculated above first
Double money = super.calcPrize (user, begin, end); / / 2: then calculate the business bonus of the current month, get the business volume of the month according to the personnel and time, and then multiply it by 3%
Double prize = TempDB.mapMonthSaleMoney.get (user) * 0.03
System.out.println (user+ "Business bonus of the month" + prize); return money + prize
}
} / * *
* decorator object, calculate cumulative bonus
* / public class SumPrizeDecorator extends Decorator {
Public SumPrizeDecorator (Component c) {super (c)
} public double calcPrize (String user, Date begin, Date end) {/ / 1: get the bonus calculated above first
Double money = super.calcPrize (user, begin, end); / / 2: then calculate the cumulative bonus. In fact, the cumulative amount of business should be obtained by the staff, and then multiplied by 0.1%.
/ / A brief demonstration, assuming that everyone's cumulative business volume is 1000000 yuan.
Double prize = 1000000 * 0.001
System.out.println (user+ "cumulative bonus" + prize); return money + prize
}
} / * *
* decorator object to calculate the current month's team business bonus
* / public class GroupPrizeDecorator extends Decorator {
Public GroupPrizeDecorator (Component c) {super (c)
} public double calcPrize (String user, Date begin, Date end) {/ / 1: get the bonus calculated above first
Double money = super.calcPrize (user, begin, end); / / 2: then calculate the team business bonus for the current month, first calculate the total business volume of the team, and then multiply it by 1%
/ / assume that they are all members of the same team.
Double group = 0; for (double d: TempDB.mapMonthSaleMoney.values ()) {
Group + = d
} double prize = group * 0.01
System.out.println (user+ "team Business bonus of the month" + prize); return money + prize
}
} / * *
* clients that use decorative mode
* / public class Client {
Public static void main (String [] args) {/ / first create a class that calculates the basic bonus, which is also the object to be decorated
Component C1 = new ConcreteComponent (); / / then decorate the calculated basic bonus, where the decorations are combined
/ / explain that it is best not to restrict the order of each decorator, that is, who decorates first and who decorates later should be the same.
/ / the function of overlaying layer by layer
/ / first combine the bonus calculation of ordinary business staff
Decorator D1 = new MonthPrizeDecorator (C1)
Decorator D2 = new SumPrizeDecorator (D1)
/ / Note: here you only need to use the last combined object to call the business method, which will be called back in turn
/ / date objects are not used, so just upload null
Double zs = d2.calcPrize ("Zhang San", null,null)
System.out.println ("= Zhang San deserves bonus:" + zs); double ls = d2.calcPrize ("Li Si", null,null)
System.out.println ("= Li Si deserves bonus:" + ls); / / if you are a business manager, you also need a bonus calculation for the calculation team.
Decorator d3 = new GroupPrizeDecorator (D2); double ww = d3.calcPrize (Wang Wu, null,null)
System.out.println ("= Manager Wang deserves bonus:" + ww)
}
}
3. Grinding design mode
1) the function of decoration mode: to add functions to objects dynamically, layer by layer packaging
2) expansion of class functions: 1. Inherit 2. Combination of objects
3) Decoration mode in Java: IO stream
InputStream is equivalent to Component.
FileInputStream,ObjectInputStream,StringBufferInputStream is equivalent to ConcreteComponent.
FilterInputStream is equivalent to Decorator.
DataInputStream,BufferedInputStream is equivalent to ConcreteDecorator.
4) decorator mode and AOP
AOP provides a mechanism for developers to describe crosscutting concerns, and can automatically implant crosscutting concerns into object-oriented software systems, thus realizing the modularization of crosscutting concerns.
AOP can encapsulate the logic that has nothing to do with business but is jointly invoked by business modules, such as transaction processing, log management, authority control, so as to reduce the repetitive code of the system, reduce the coupling between modules, and facilitate future maintenance and operation.
A more important change in AOP is the change in thinking (master-slave transposition), which turns the original active function module into passive waiting.
/ * *
* the business interface of commodity sales management is equivalent to Component
* / public interface GoodsSaleEbi {
/ * *
* Save sales information. Originally, there should be multiple sales data, which is too troublesome. For demonstration, keep it simple.
* @ param user operator
* @ param customer customer
* @ param saleModel sales data
* @ return whether it is saved successfully
, /
Public boolean sale (String user,String customer,SaleModel saleModel)
} / * *
* encapsulate the data of the sales order and simply indicate it.
* / public class SaleModel {
/ * *
* goods sold
, /
Private String goods; / * *
* quantity sold
, /
Private int saleNum; public String getGoods () {return goods
} public void setGoods (String goods) {this.goods = goods
} public int getSaleNum () {return saleNum
} public void setSaleNum (int saleNum) {this.saleNum = saleNum
} public String toString () {return "Commodity name =" + goods+ ", purchase quantity =" + saleNum
}
} / * *
* Business object
* / public class GoodsSaleEbo implements GoodsSaleEbi {
Public boolean sale (String user,String customer, SaleModel saleModel) {
System.out.println (user+ "saves sales data for" + customer+ "purchase" + saleModel+ "); return true
}
} / * *
* the interface of the decorator needs to implement the same interface as the decorated object
* / public abstract class Decorator implements GoodsSaleEbi {
/ * *
* hold the decorated component object
, /
Protected GoodsSaleEbi ebi; / * *
* pass in the decorated object through the construction method
* @ param ebi objects to be decorated
, /
Public Decorator (GoodsSaleEbi ebi) {this.ebi = ebi
}
} / * *
* implement permission control
* / public class CheckDecorator extends Decorator {
Public CheckDecorator (GoodsSaleEbi ebi) {super (ebi)
} public boolean sale (String user,String customer, SaleModel saleModel) {/ / keep it simple, just let Zhang San perform this function.
If (! "Zhang San" .equals (user)) {
System.out.println ("Sorry" + user+ ", you do not have permission to save the sales order"); / / the function of the decorated object is no longer called.
Return false
} else {return this.ebi.sale (user, customer, saleModel)
}
}
} / * *
* implement logging
* / public class LogDecorator extends Decorator {
Public LogDecorator (GoodsSaleEbi ebi) {super (ebi)
} public boolean sale (String user,String customer, SaleModel saleModel) {/ / perform business functions
Boolean f = this.ebi.sale (user, customer, saleModel); / / log after performing the business function
DateFormat df = new SimpleDateFormat ("yyyy-MM-dd HH:mm:ss SSS")
System.out.println ("logging:" + user+ "keeps a sales record at" + df.format (new Date ()) + ", the customer is" + customer+ ", and the purchase record is" + saleModel); return f
}
} public class Client {
Public static void main (String [] args) {/ / get the business interface, composite decorator
GoodsSaleEbi ebi = new CheckDecorator (new LogDecorator (new GoodsSaleEbo (); / / prepare test data
SaleModel saleModel = new SaleModel ()
SaleModel.setGoods ("Moto Mobile phone")
SaleModel.setSaleNum (2); / / invoke business functions
Ebi.sale ("Zhang San", "Zhang Sanfeng", saleModel)
Ebi.sale ("Li Si", "Zhang Sanfeng", saleModel)
}
}
5) the essence of decorator pattern: dynamic combination
At this point, the study on "how to use the decoration mode in java" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 252
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.