Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

How to write Java decorator

Shulou Source: shulou.com Published: 2022-06-01 04:25:32 10月04日 Update

This article mainly introduces the Java decorator how to write the relevant knowledge, the content is detailed and easy to understand, the operation is simple and fast, has a certain reference value, I believe that everyone after reading this Java decorator how to write the article will have a harvest, let's take a look.

/ simulated coffee / / 1. Abstract component: abstract object (interface or abstract parent class) that needs to be decorated / / 2. Specific components: objects to be decorated / / 3. Abstract Decoration Class: contains references to abstract components and decorates common methods / / 4. Specific decoration class: public class TestDecoretorTwo {public static void main (String [] args) {Drink coffee = new coffee (); Drink suger = new Suger (coffee); System.out.println (suger.cost () + "-->" + suger.Info ()); Drink milk = new Milk (coffee); System.out.println (milk.cost () + "-->" + milk.Info ()); Drink milk1 = new Milk (suger) System.out.println (milk1.cost () + "-->" + milk1.Info ());} / / 1. Abstract component interface Drink {int cost (); String Info ();} / / 2. Specific components: class coffee implements Drink {String name= "original coffee"; public int cost () {return 10;} @ Override public String Info () {return name;}} / / 3. Abstract Decoration Class: class Decorate implements Drink {/ / A reference to abstract components private Drink drink;public Decorate (Drink drink) {/ / here is a constructor (this) this.drink = drink;} @ Override public int cost () {return this.drink.cost ();} @ Override public String Info () {return this.drink.Info ();} / / 4. Specific decoration class 1: class Milk extends Decorate {public Milk (Drink drink) {/ / here is a constructor, (super) super (drink);} @ Override public int cost () {return super.cost () * 4;} @ Override public String Info () {return super.Info () + "added milk";}} / / 4. Specific decoration class 2: class Suger extends Decorate {public Suger (Drink drink) {super (drink);} @ Override public int cost () {return super.cost () * 2;} @ Override public String Info () {return super.Info () + "added sugar";}}

Output result

20Mutual coffee with sucrose added

40Mutual coffee with milk added.

80Mutual coffee with sucrose and milk

This is the end of the article on "how to write Java decorator". Thank you for reading! I believe that everyone has a certain understanding of the knowledge of "how to write Java decorator". If you want to learn more, you are welcome to follow the industry information channel.

Tags: Components coffee original flavor object milk knowledge sugar content article constructor value interface easy to operate article method easy to understand more see results industry Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno MySQL Microsoft vpn MariaDB macOS