I've made a handy little chart of how some parts of your brain are messing with other parts (and subverting your consciousness).
Something sets you off. You're at the coffee shop "Oh, they have cake!". Totally unexpected, I know, and a second ago you didn't want cake, you weren't even thinking about cake. But now the craving has been triggered and you really want cake. Now it can go two ways: you buy the cake or you don't. If you buy it and eat it you will experience a moment of joy (because cake is what we called hyperpalatable) and your brain will respond with a craving again the next time you see cake. If you don't buy and eat the cake things get interesting. Because the next time you experience the trigger the craving actually becomes stronger. Your brain is trying harder since the last time the craving wasn't strong enough to elicit cake. And if you then give in you are reinforcing stronger cravings. But if you don't your brain will at some point give up. Cravings turn out to be fruitless and there's no point in making you experience them.
tl;dr If you have bad cravings and you want them to go away then you can only have sweets if you don't want them. It sucks, I know.
To be honest I don't think you can get entirely rid of cravings. They are probably tied in with the normal hunger system and helps you make sure you get enough to eat. And I only really think they are a problem when they have you eating things you don't actually want. When I can say yes and no to treats based on how I know they affect me in the long term then I'm happy. And when I can't that's when I know I have to reset the system and ditch all the treats so I can function normally again (no, an apple or similar isn't a treat but based on how I respond to grapes I would have to say that they are).
Additional reading: What Shamu Taught Me About a Happy Marriage an article about positive reinforcement and extinction in everyday life (there's a book too). All of Stephan Guyenet's blog on food reward.